TIMEX TIMEX - 1 month ago 5x
Python Question

In Python, how do I loop through the dictionary and change the value if it equals something?

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.