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:
{k: v if v is not None else "" for k, v in mydict.items()}
It's worth a note that the second example can be simplified, as iterating directly over mydict
will provide the keys, so no need for mydict.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 than items()
as it does not produce a list - 3.x users like myself don't need to worry as items()
produces a dictionary view, which is lazy.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With