Python 编辑字典列表中的值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4291236/
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
Edit the values in a list of dictionaries?
提问by dave
my_dicts = [
{ 'key1' : 'value1',
'key2' : 'value2' },
{ 'key1' : 'value1',
'key2' : 'value2' },
{ 'key1' : 'value1',
'key2' : 'value2' }]
What would be the most efficient way to replace all instances of 'value2' with 'value3' ?
用 'value3' 替换所有 'value2' 实例的最有效方法是什么?
回答by Sven Marnach
I did not do any timings, but you probably can't get much better than
我没有做任何计时,但你可能不会比
for d in my_dicts:
d.update((k, "value3") for k, v in d.iteritems() if v == "value2")
Update for Python3
Python3 更新
for d in my_dicts:
d.update((k, "value3") for k, v in d.items() if v == "value2")
回答by martineau
Here's a very general answer designed to handle multiple occurrences of multiple values in large dictionaries. Handling simpler more specific cases and/or with small dictionaries -- like your example -- could be done significantly faster.
这是一个非常通用的答案,旨在处理大型字典中多个值的多次出现。处理更简单的更具体的案例和/或使用小词典——比如你的例子——可以更快地完成。
from collections import defaultdict
my_dicts = [
{ 'key1' : 'value1',
'key2' : 'value2' },
{ 'key1' : 'value1',
'key2' : 'value2',
'key3' : 'value2' }, # dup added for testing
{ 'key1' : 'value1',
'key2' : 'value2' }]
def reverse(dct):
""" Create dictionary mapping each value to list of one or more keys """
ret = defaultdict(list)
for key,val in dct.iteritems():
ret[val].append(key)
return ret
def replace_values(dicts, replacments):
""" Replace values in each dict in dicts """
for dct in dicts:
revdict = reverse(dct)
for oldval,newval in replacments.iteritems():
for key in revdict.get(oldval, []):
dct[key] = newval
replace_values(my_dicts, {'value2':'value3'})
print my_dicts
# [{'key2': 'value3', 'key1': 'value1'},
# {'key3': 'value3', 'key2': 'value3', 'key1': 'value1'},
# {'key2': 'value3', 'key1': 'value1'}]
回答by Brent
for x in my_dicts:
for y in x:
if x.get(y) == 'value2':
x.update({y: "value3"})

