首页 > 解决方案 > 如何检查列表是否包含具有相同键的dict元素

问题描述

我想检查我的列表是否包含具有相同两个键值的元素。例如,我想通过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

标签: pythonpython-3.xitertools

解决方案


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

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

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


推荐阅读