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

后端 未结 3 367
长情又很酷
长情又很酷 2020-12-04 14:10

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 Non         


        
3条回答
  •  南笙
    南笙 (楼主)
    2020-12-04 14:37

    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.

提交回复
热议问题