在Python中,如何循环使用字典,如果它等于某事,则更改值? [英] In Python, how do I loop through the dictionary and change the value if it equals something?

查看:575
本文介绍了在Python中,如何循环使用字典,如果它等于某事,则更改值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果值为None,我想将其更改为(空字符串)。

If the value is None, I'd like to change it to "" (empty string).

我这样开始,但我忘了: / p>

I start off like this, but I forget:

for k, v in mydict.items():
    if v is None:
... right?


推荐答案

for k, v in mydict.iteritems():
    if v is None:
        mydict[k] = ''

在一般情况下,例如如果您正在添加或删除键,则可能不会更改您正在循环的容器的结构,因此使用项目循环单独列表副本它可能是谨慎的 - 但是在给定的现有索引中分配不同的值不不会导致任何问题,所以在Python 2.any中,最好使用 iteritems

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.

这篇关于在Python中,如何循环使用字典,如果它等于某事,则更改值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆