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

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

    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.

提交回复
热议问题