gpt4 book ai didi

python - 如果两个列表具有共同的键值对,如何合并两个列表中的字典?

转载 作者:太空宇宙 更新时间:2023-11-03 18:30:43 24 4
gpt4 key购买 nike

我有两个字典列表。每个列表中的每个字典都有一个 id 字段。我想将列表 1 中的词典与列表 2 中的词典合并,前提是它们共享一个共同的“id”

L1 = [{'id':'123','field1':'abc','field2':'def','field3':'ghi'},{'id':'456','field1':'jkl','field2':'mno','field3':'pqr'},{'id':'789','field1':'stu','field2':'vwx','field3':'yz'}] 
L2 = [{'field4':'aaa','field5':'bbb','field6':'ccc','field7':'ddd','id':'101'},{'field4':'eee','field5':'fff','field6':'ggg','field7':'hhh','id':'789'},{'field4':'iii','field5':'jjj','field6':'kkk','field7':'lll','id':'456'},{'field4':'mmm','field5':'nnn','field6':'ooo','field7':'ppp','id':'123'}]


DesiredList = [{'id':'123','field1':'abc','field2':'def','field3':'ghi','field4':'mmm','field5':'nnn','field6':'ooo','field7':'ppp'},{'id':'456','field1':'jkl','field2':'mno','field3':'pqr','field4':'iii','field5':'jjj','field6':'kkk','field7':'lll'},{'id':'789','field1':'stu','field2':'vwx','field3':'yz','field4':'eee','field5':'fff','field6':'ggg','field7':'hhh'},{'field4':'aaa','field5':'bbb','field6':'ccc','field7':'ddd','id':'101'}]

我已经完成了

DesiredList = []
for Dict2 in L2:
for Dict1 in L1:
if Dict1['id'] == Dict2['id']:
Dict2.update(Dict1)
DesiredList.append(Dict2)

这会导致

  >>>DesiredList 
DesiredList = [{'id': '101', 'field6': 'ccc', 'field7': 'ddd', 'field4': 'aaa', 'field5': 'bbb'}, {'field2': 'vwx', 'field3': 'yz', 'field1': 'stu', 'field6': 'ggg', 'field7': 'hhh', 'field4': 'eee', 'field5': 'fff', 'id': '789'}, {'field2': 'mno', 'field3': 'pqr', 'field1': 'jkl', 'field6': 'kkk', 'field7': 'lll', 'field4': 'iii', 'field5': 'jjj', 'id': '456'}, {'field2': 'def', 'field3': 'ghi', 'field1': 'abc', 'field6': 'ooo', 'field7': 'ppp', 'field4': 'mmm', 'field5': 'nnn', 'id': '123'}]

必须有一种更快、更高效的更好方法来做到这一点。

最佳答案

如果你正在寻找一种有效的方法,你可以这样做

from itertools import chain
from collections import defaultdict

result = defaultdict(dict)

for c_dict in chain(L1, L2):
result[c_dict["id"]].update(c_dict)

print result.values()

输出

[{'field1': 'abc',
'field2': 'def',
'field3': 'ghi',
'field4': 'mmm',
'field5': 'nnn',
'field6': 'ooo',
'field7': 'ppp',
'id': '123'},
{'field1': 'stu',
'field2': 'vwx',
'field3': 'yz',
'field4': 'eee',
'field5': 'fff',
'field6': 'ggg',
'field7': 'hhh',
'id': '789'},
{'field1': 'jkl',
'field2': 'mno',
'field3': 'pqr',
'field4': 'iii',
'field5': 'jjj',
'field6': 'kkk',
'field7': 'lll',
'id': '456'},
{'field4': 'aaa',
'field5': 'bbb',
'field6': 'ccc',
'field7': 'ddd',
'id': '101'}]

关于python - 如果两个列表具有共同的键值对,如何合并两个列表中的字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22425591/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com