基于键值对的Python更新字典

时间:2015-11-18 15:29:28

标签: python json list dictionary

这个问题是如何检查两个字典列表和相同的键,并用其他字典中的键值对更新主字典。

第一本词典

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

2 个答案:

答案 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'}]