【问题标题】:How to check if list contains dict element with same key如何检查列表是否包含具有相同键的dict元素
【发布时间】:2020-10-22 12:09:03
【问题描述】:

我想检查我的列表是否包含具有相同两个键值的元素。 例如我想通过categoryweight在下面的列表中进行聚合:

products = [
    {"id": 1, "category": "Furniture", "weight": 3.22},
    {"id": 2, "category": "Furniture", "weight": 4.55},
    {"id": 3, "category": "Furniture", "weight": 3.22},
    {"id": 4, "category": "Garden", "weight": 3.22},
]

上面的例子应该返回 True

products = [
    {"id": 1, "category": "Furniture", "weight": 3.22},
    {"id": 2, "category": "Furniture", "weight": 4.55},
    {"id": 4, "category": "Garden", "weight": 3.22},
]

上面的例子应该返回 False

【问题讨论】:

  • 请用您尝试过的代码更新您的问题。
  • 你想如何比较两个字典?通过键'类别'和'重量'而不是'id'?
  • 看看itertools.groupby。您可以按类别和权重进行分组,然后查看任何组是否包含多个元素。
  • @adirabargil 是的
  • @chepner 这需要首先按所需的键功能进行排序,这很好,但是 O(n log n)。

标签: python python-3.x itertools


【解决方案1】:

一种可能的方法是首先编写一个通用函数来检测可迭代对象是否包含重复项:

def has_duplicates(it):
    """Returns whether the iterable contains any duplicates.

    The items of the iterable need to be hashable."""
    seen = set()
    for x in it:
        if x in seen:
            return True
        seen.add(x)
    return False

要将此函数应用于您的问题,您需要提取要比较的键,例如

from operator import itemgetter
key_function = itemgetter("category", "weight")
print(has_duplicates(map(key_function, products)))

这会为您的第一个示例打印True,为第二个示例打印False

请注意,这将比较确切的身份,这对于浮点数通常是一个坏主意。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-30
    • 2016-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-22
    • 2016-01-30
    相关资源
    最近更新 更多