【问题标题】:How to compare two lists of dicts in Python and fetch difference如何在 Python 中比较两个字典列表并获取差异
【发布时间】:2022-06-28 22:23:53
【问题描述】:

我是 python 新手。在 Python 中,我想比较两个字典列表

下面是我要比较的 2 个字典列表,基于键“zrepcode”和 id 是数字“1”、“3”和“4”...

代码sn-p如下:

List1 = [{"3":[{"period":"P13","value":10,"year":2022}],"zrepcode":"55"},{"1":[{"period":"P10","value":5,"year":2023}],"zrepcode":"55"}]

List2 = [{"1":[{"period":"P1","value":10,"year":2023},{"period":"P2","value":5,"year":2023}],"zrepcode":"55"},{"3":[{"period":"P1","value":4,"year":2023},{"period":"P2","value":7,"year":2023}],"zrepcode":"55"},{"4":[{"period":"P1","value":10,"year":2023}],"zrepcode":"55"}]

比较后,我们需要list2中唯一的字典列表。

res = [{"4":[{"period":"P1","value":10,"year":2023}],"zrepcode":"55"}]

这是预期的输出,现在我不知道我是如何得到这个的。

【问题讨论】:

    标签: python python-3.x list sorting dictionary


    【解决方案1】:

    您可以使用列表推导来过滤列表。

    [x for x in list if condition]
    

    和 any() 来查看列表是否有任何匹配条件的元素

    any(condition for y in list)
    

    或者在你的情况下,因为你想要那些在其他人中不存在的

    [x for x in list2 if not any(your_condition for y in list1)]
    

    要检查两个元素是否具有相同的 zrepcode 值,您可以像这样比较它们

    x['zrepcode'] == y['zrepcode']
    

    由于您的另一个比较点是一个键,并且每个键只有两个,因此您可以比较两者的键

    x.keys() == y.keys()
    

    结合一切

    [x for x in list2 if not any(x['zrepcode'] == y['zrepcode'] and x.keys() == y.keys() for y in list1)]
    

    【讨论】:

      猜你喜欢
      • 2019-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-12
      • 1970-01-01
      • 1970-01-01
      • 2014-02-26
      相关资源
      最近更新 更多