简体   繁体   English

如何合并键上的两个字典列表-Python?

[英]How to merge two dict lists on key - Python?

I have two dict lists that I am trying to merge on a unique key but I cannot get my head around how to approach this. 我有两个字典列表,我试图在一个唯一的键上进行合并,但是我无法理解如何解决这个问题。

dict 1: 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'}]}

dict 2: dict 2:

B = {'1': [{'l_1': 'www.l_1', 'l_2': 'www.l_2'}], 
'2': [{'l_1': 'www.myl_1', 'l_2': 'www.myl_2'}]}

What I am trying to achieve: 我想要达到的目标:

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

Below is the code that I have written so far. 以下是我到目前为止编写的代码。 But it does not provide me with the desired result.. 但这不能为我提供理想的结果。

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)

You can use itertools.product to merge dict values from corresponding keys and then use Python 3's dict merge syntax: 您可以使用itertools.product合并对应键中的dict值,然后使用Python 3的dict合并语法:

from itertools import product

dct =  {k: [{**d1, **d2} for d1, d2 in product(v, B[k])] 
                                           for k, v in A.items()}

In Python 2, you can apply a comprehension on the tuples from product, and build a merged dict from the elements: 在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()}

{'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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM