TIMEX TIMEX - 1 year ago 63
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?

Answer Source
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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download