【问题标题】:merging a list of nested dictionaries合并嵌套字典列表
【发布时间】:2018-03-25 08:19:27
【问题描述】:

我有两个字典列表,如下例所示

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

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

我想要如下格式的结果

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

list1 和 list2 的大小可以是 10000 的。 List3 将是 list1 和 list2 的并集。解决此问题的最佳 Python 解决方案可能是什么。

【问题讨论】:

  • 当列表有“10000”个元素时,你如何“联合”列表?你想联合每对字典,即产品,在列表 3 中产生 10,000²=100,000,000 个字典吗?或者你总是将list1中的所有dicts合并到list2中的所有dicts中,导致list 3中只有10,000个dicts?您应该提供更多解释和/或示例。
  • 您可能需要重新阅读How to Ask 和minimal reproducible example。

标签: python list dictionary


【解决方案1】:

你没有写任何代码,所以我不会写一个完整的解决方案。你需要zip_longest 和dict merging。

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})

它输出:

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

现在您已经合并了内部字典,您需要做的就是将它们打包到另一个 dict 中,并以 "pdpData" 为键,然后将这些字典打包到一个列表中。

【讨论】:

    【解决方案2】:
    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)
    

    输出

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

    【讨论】:

    • 你失去了订单,但是。
    • OP 想要一个有序的列表。您使用默认字典,它是无序的。您不能保证l3 的顺序正确。此外,您使用值 'a' 作为索引,这似乎不是所需的行为。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-18
    • 2022-01-19
    • 2021-04-26
    • 2021-02-12
    • 2011-05-13
    相关资源
    最近更新 更多