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

后端 未结 3 359
长情又很酷
长情又很酷 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:26

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

提交回复
热议问题