如何检查列表是否包含具有相同键的dict元素

时间:2020-10-22 12:09:03

标签: python python-3.x itertools

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

1 个答案:

答案 0 :(得分:2)

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

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

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