Is there any advantage to using the first block of code over the second one when iterating over a dictionary?
for k, v in mydict.items():
if v == None:
mydict[k] = ''
and
for k in mydict.keys():
if mydict[k] == None:
mydict[k] = ''
The first method is arguably clearer and easier to read, so I would always recommend it over the latter.
That said, in a simple case like this, the better option would be a dictionary comprehension:
It’s worth a note that the second example can be simplified, as iterating directly over
mydictwill provide the keys, so no need formydict.keys()(which is mainly useful for when you want the set of keys for another purpose, not iteration).(As jathanism notes in the comments, in older versions of Python (2.x), using
iteritems()is a better option thanitems()as it does not produce a list – 3.x users like myself don’t need to worry asitems()produces a dictionary view, which is lazy.)