Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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? 
like image 980
TIMEX Avatar asked Feb 23 '10 01:02

TIMEX


People also ask

Can I change a value in a dictionary Python?

Change Dictionary Values in Python Using the dict. update() Method. In this method, we pass the new key-value pairs to the update() method of the dictionary object. We can change one and more key-value pairs using the dict.

How do you iterate through a value in a dictionary Python?

To iterate through a dictionary in Python, there are four main approaches you can use: create a for loop, use items() to iterate through a dictionary's key-value pairs, use keys() to iterate through a dictionary's keys, or use values() to iterate through a dictionary's values.

How do you access dictionary values in a for loop?

In Python, to iterate the dictionary ( dict ) with a for loop, use keys() , values() , items() methods. You can also get a list of all keys and values in the dictionary with those methods and list() .


2 Answers

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.

like image 146
Alex Martelli Avatar answered Oct 03 '22 07:10

Alex Martelli


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.

like image 22
PaulMcG Avatar answered Oct 03 '22 08:10

PaulMcG