If the value is None, I'd like to change it to "" (empty string).
I start off like this, but I forget:
for k, v in mydict.items():
if v is None:
... right?
If the value is None, I'd like to change it to "" (empty string).
I start off like this, but I forget:
for k, v in mydict.items():
if v is None:
... right?
for k, v in mydict.iteritems():
if v is None:
mydict[k] = ''
In a more general case, e.g. if you were adding or removing keys, it might not be safe to change the structure of the container you're looping on -- so using items
to loop on an independent list copy thereof might be prudent -- but assigning a different value at a given existing index does not incur any problem, so, in Python 2.any, it's better to use iteritems
.
Comprehensions are usually faster, and this has the advantage of not editing mydict during the iteration
mydict = dict([(k, v if v else "") for k,v in mydict.items()])