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

PythonDictionary

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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.

In Python3 however the code gives AttributeError: 'dict' object has no attribute 'iteritems' error. Use items() instead of iteritems() here.

Refer to this post.

Solution 2 - Python

You could create a dict comprehension of just the elements whose values are None, and then update back into the original:

tmp = dict((k,"") for k,v in mydict.iteritems() if v is None)
mydict.update(tmp)

Update - did some performance tests

Well, after trying dicts of from 100 to 10,000 items, with varying percentage of None values, the performance of Alex's solution is across-the-board about twice as fast as this solution.

Solution 3 - Python

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())

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTIMEXView Question on Stackoverflow
Solution 1 - PythonAlex MartelliView Answer on Stackoverflow
Solution 2 - PythonPaulMcGView Answer on Stackoverflow
Solution 3 - PythonbuckleyView Answer on Stackoverflow