如何在key-Python上合并两个dict列表?
我有两个dict列表,我正试图将它们合并到一个唯一的键上,但我不知道该如何处理 第1条:如何在key-Python上合并两个dict列表?,python,dictionary,Python,Dictionary,我有两个dict列表,我正试图将它们合并到一个唯一的键上,但我不知道该如何处理 第1条: A = {'1': [{'A': 'A_1', 'start': 'S'}, {'A': 'A_2', 'start': 'M'}], '2': [{'A': 'A_1', 'start': 'S'}, {'A': 'A_2', 'start': 'M'}]} 第2条: B = {'1': [{'l_1': 'www.l_1', 'l_2': 'www.l_2'}], '2': [{'l_1': 'w
A = {'1': [{'A': 'A_1', 'start': 'S'}, {'A': 'A_2', 'start': 'M'}],
'2': [{'A': 'A_1', 'start': 'S'}, {'A': 'A_2', 'start': 'M'}]}
第2条:
B = {'1': [{'l_1': 'www.l_1', 'l_2': 'www.l_2'}],
'2': [{'l_1': 'www.myl_1', 'l_2': 'www.myl_2'}]}
我正在努力实现的目标:
combined = {'1': [{'A': 'A_1', 'start': 'S', 'l_1': 'www.l_1', 'l_2': 'www.l_2'}, {'A': 'A_2', 'start': 'M', 'l_1': 'www.l_1', 'l_2': 'www.l_2'}],
'2': [{'A': 'A_1', 'start': 'S', 'l_1': 'www.myl_1', 'l_2': 'www.myl_2'}, {'A': 'A_2', 'start': 'M', 'l_1': 'www.myl_1', 'l_2': 'www.myl_2'}]}
下面是到目前为止我编写的代码。但是它并没有给我提供想要的结果
from itertools import chain
from collections import defaultdict
dict3 = defaultdict(list)
for k, v in chain(A.items(), B.items()):
dict3[k].append(v)
print(dict3)
您可以使用合并来自相应键的dict值,然后使用Python 3的dict merge语法:
from itertools import product
dct = {k: [{**d1, **d2} for d1, d2 in product(v, B[k])]
for k, v in A.items()}
在Python 2中,您可以对product中的元组进行理解,并根据以下元素构建合并的dict:
dct = {key: [{k: v for d in tup for k, v in d.items()}
for tup in product(val, B[key])]
for key, val in A.items()}
我现在有点忙,但是查看一下
dict.update
来做大量的工作,而不是重复每个键。非常感谢您的回答!
{'1': [{'A': 'A_1', 'l_1': 'www.l_1', 'l_2': 'www.l_2', 'start': 'S'},
{'A': 'A_2', 'l_1': 'www.l_1', 'l_2': 'www.l_2', 'start': 'M'}],
'2': [{'A': 'A_1', 'l_1': 'www.myl_1', 'l_2': 'www.myl_2', 'start': 'S'},
{'A': 'A_2', 'l_1': 'www.myl_1', 'l_2': 'www.myl_2', 'start': 'M'}]}
for i in a:
if i in b:
for j in range(min(len(a[i]),len(b[i]))):
a[i][j]=dict(a[i][j].items()+b[i][j].items()) #re-assign after combining
if len(b[i])>len(a[i]): # length case
for j in range(len(a[i]),len(b[i])):
a[i].append(b[i][j])
for i in b: # if not in a
if i not in a:
a[i]=b[i]
print a