Python 如何迭代和修改字典中的值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4992739/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 18:30:43 来源:igfitidea点击:
How can I iterate over and modify the values in a dict?
提问by gomzi
records = {'foo':foo, 'bar':bar, 'baz':baz}
I want to change the values to 0if it is None. How can I do this?
我想将值更改0为None. 我怎样才能做到这一点?
eg:
例如:
records = {'foo':None, 'bar':None, 'baz':1}
I want to change fooand barto 0.
Final dict:
我想改变foo和bar到0。最终判词:
records = {'foo':0, 'bar':0, 'baz':1}
采纳答案by Nick Dandoulakis
Another way
其它的办法
records.update((k, 0) for k,v in records.iteritems() if v is None)
Example
例子
>>> records
{'bar': None, 'baz': 1, 'foo': None}
>>> records.update((k, 0) for k,v in records.iteritems() if v is None)
>>> records
{'bar': 0, 'baz': 1, 'foo': 0}
回答by Sven Marnach
Try
尝试
for key, value in records.iteritems():
if value is None:
records[key] = 0
回答by Alex Reynolds
for k, v in records.items():
if v is None:
records[k] = 0
回答by S.Lott
for k in records:
if records[k] is None:
records[k] = 0
回答by Deestan
If you want to intimidate or annoy other code maintainers, there's an ugly one-liner that will do the trick:
如果你想恐吓或惹恼其他代码维护者,有一个丑陋的单行代码可以解决这个问题:
records.update(map(lambda (k,v):(k,{v:v,None:0}[v]), records.items()))
Example use:
使用示例:
>>> records = {"hey":None, "you":0}
>>> records.update(map(lambda (k,v):(k,{v:v,None:0}[v]), records.items()))
>>> records
{'you': 0, 'hey': 0}
回答by S.Lott
records = dict( ( k,0 if v is None else v ) for k, v in records.items() )
def zero_if_none( x ):
return 0 if x is None else x
records = dict( ( k, zero_if_none( records[k] ) ) for k in records )

