这个问题是如何检查两个字典列表和相同的键,并用其他字典中的键值对更新主字典。
main = [
{'country': u'CYPRUS', 'naziv': 'AKEL', 'FCI': 2},
{'country': u'CYPRUS', 'naziv': 'DIKO', 'FCI': 4},
]
second = [
{'likes': '8625.00', 'talks': '1215.00', 'naziv': 'AKEL'},
{'likes': '2746.00', 'talks': 0, 'naziv': 'DIKO'},
]
output = [
{'country': u'CYPRUS', 'naziv': 'AKEL', 'FCI': 2,'likes': '8625.00', 'talks': '1215.00'}
{'country': u'CYPRUS', 'naziv': 'DIKO', 'FCI': 4,'likes': '2746.00', 'talks': 0},
]
有没有快速的方法来做到这一点。我正在尝试更新一个字典但不起作用。
for dt, k in itertools.groupby(sorted(second, key=itemgetter('naziv')), key=itemgetter('naziv')):
maindict = {'naziv': dt}
for d in k:
maindict.update(d)
main.append(maindict)
Python 2.7
答案 0 :(得分:2)
另一个可能是 -
import itertools
main = [
{'country': u'CYPRUS', 'naziv': 'AKEL', 'FCI': 2},
{'country': u'CYPRUS', 'naziv': 'DIKO', 'FCI': 4},
]
second = [
{'likes': '8625.00', 'talks': '1215.00', 'naziv': 'AKEL'},
{'likes': '2746.00', 'talks': 0, 'naziv': 'DIKO'},
]
lst = sorted(itertools.chain(main,second), key=lambda x:x['naziv'])
list_c = []
for k,v in itertools.groupby(lst, key=lambda x:x['naziv']):
d = {}
for dct in v:
d.update(dct)
list_c.append(d)
print list_c
“无耻的mgilson副本”
答案 1 :(得分:2)
为什么不直接用main
字典更新key
字典列表second
字典,只需这样:
>>> for i,d in enumerate(second):
main[i].update(second[i])
>>> main
[{'likes': '8625.00', 'FCI': 2, 'talks': '1215.00', 'country': u'CYPRUS', 'naziv': 'AKEL'}, {'likes': '2746.00', 'FCI': 4, 'talks': 0, 'country': u'CYPRUS', 'naziv': 'DIKO'}]