简体   繁体   English

合并嵌套字典列表

[英]merging a list of nested dictionaries

I have two list of dictionaries as shown in example below 我有两个字典列表,如下例所示

list1=[
        {
            "pdpData":{
                "a":1,
                "b":2
            }
        }
    ]

list2=[
    {
        "pdpData":{
            "a":1,
            "c":3
        }
    },
    {
        "pdpData":{
            "a":2,
            "b":3
        }
    }
]

I want the result as shown in the format below 我想要以下格式的结果

list3=[
{
    "pdpData":{
        "a":1,
        "b":2,
        "c":3
    }
},
{
    "pdpData":{
        "a":2,
        "b":3
    }
}
]

The size of list1 and list2 could be in 10000's. list1和list2的大小可以为10000。 List3 would be the union of list1 and list2. List3将是list1和list2的并集。 What could be the best pythonic solutions to solve this problem. 什么是解决此问题的最佳pythonic解决方案。

You didn't write any code, so I won't write a complete solution. 您没有编写任何代码,因此我不会编写完整的解决方案。 You'll need zip_longest and dict merging . 您需要zip_longestdict合并

from itertools import zip_longest

list1=[
        {
            "pdpData":{
                "a":1,
                "b":2
            }
        }
    ]

list2=[
    {
        "pdpData":{
            "a":1,
            "c":3
        }
    },
    {
        "pdpData":{
            "a":2,
            "b":3
        }
    }
]


for d1, d2 in zip_longest(list1, list2):
    dd1 = d1.get("pdpData", {}) if d1 else {}
    dd2 = d2.get("pdpData", {}) if d2 else {}
    print({**dd1, **dd2})

It outputs : 输出:

{'a': 1, 'b': 2, 'c': 3}
{'a': 2, 'b': 3}

Now that you have merged inner-dicts, all you need to do is pack them into another dict with "pdpData" as key, and pack those dicts into a list. 现在,你已经合并了内类型的字典,所有你需要做的就是收拾他们到另一个dict"pdpData"为重点,和包装这些类型的字典到列表中。

from collections import defaultdict

d = defaultdict(dict)
for l in (l1, l2):
    for elem in l:
        d[elem['pdpData']['a']].update(elem['pdpData'])
l3 = d.values()

print(l3)

Output 产量

dict_values([{'a': 1, 'b': 2, 'c': 3}, {'a': 2, 'b': 3}])

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

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