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

If the value is "No", I would like to change it to "" (empty line).

I start like this, but I forget:

for k, v in mydict.items(): if v is None: ... right? 
+57
python dictionary
Feb 23 '10 at 1:19
source share
3 answers
 for k, v in mydict.iteritems(): if v is None: mydict[k] = '' 

In the more general case, for example, if you add or remove keys, it may not be safe to change the structure of the container on which you work with the loop - so it would be wise to use items to loop in an independent copy of the list. but assigning a different value for this existing index does not cause any problems, so in Python 2.any it is better to use iteritems .

However, in Python3, the code throws AttributeError: 'dict' object has no attribute 'iteritems' AttributeError: 'dict' object has no attribute 'iteritems' . Use items() instead of iteritems() here.

Refer to this post.

+113
Feb 23 '10 at 1:21
source share

You can create a dict definition only for elements whose values ​​are None, and then update them back to the original:

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

Refresh - performed some performance tests

Well, after you tried dictations from 100 to 10,000 elements with a variable percentage of None values, the performance of the Alex solution is almost twice as fast as this solution.

+14
Feb 23 '10 at 2:16
source share

Understanding tends to be faster, and this has the advantage of not editing mydict during iteration:

 mydict = dict((k, v if v else '') for k, v in mydict.items()) 
+8
Feb 23 '10 at 1:27
source share



All Articles