my_dicts = [
{ 'key1' : 'value1',
'key2' : 'value2' },
{ 'key1' : 'value1',
'key2' : 'value2' },
{ 'key1' : 'value1',
'key2' : 'value2' }]
用'value3'替换'value2'的所有实例的最有效方法是什么?
答案 0 :(得分:34)
我没有做任何时间,但你可能不会比
好多了for d in my_dicts:
d.update((k, "value3") for k, v in d.iteritems() if v == "value2")
Python3的更新
for d in my_dicts:
d.update((k, "value3") for k, v in d.items() if v == "value2")
答案 1 :(得分:2)
var firstArray = ["k","d","r","r","p","k","b","p","k","k"]
var secondArray = ["k","d","r","s","d","r","b","c"]
let filterArray = firstArray.filter { secondArray.contains($0) }
let filterArray1 = firstArray.filter { !secondArray.contains($0) }
let filterIndex = firstArray.enumerated().filter { $0.element == "k" }.map { $0.offset }
print(filterArray) --> // ["k", "d", "r", "r", "k", "b", "k", "k"]
print(filterArray1) --> // ["p", "p"]
print(filterIndex) --> // [0, 5, 8, 9]
答案 2 :(得分:1)
这是一个非常通用的答案,旨在处理大字典中多个值的多次出现。处理更简单的更具体的案例和/或使用小词典(如您的示例)可以更快地完成。
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'}]
答案 3 :(得分:0)
Python3.7 dict理解(尽管会返回深层副本):
update = {'key2':'value3'}
new_dicts = [{**d,**update} for d in my_dicts]
答案 4 :(得分:-1)
编辑:
或者
for item in my_dicts:
item['key2'] = 'value3'