TransWikia.com

How to check if list contains dict element with same key

Stack Overflow Asked by Radosław Hryniewicki on February 1, 2021

I want to check if my list contains elements with the same two key values.
For example I want to aggregate through category and weight on the list below:

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},
]

Example above should return True

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

Example above should return False

One Answer

One possible approach is to first write a generic function to detect whether an iterable contains duplicates:

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

To apply this function to your problem, you need to extract the keys you want to compare, e.g.

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

This prints True for your first example and False for the second.

Note that this will compare for exact identity, which for floating-point numbers in general is a bad idea.

Answered by Sven Marnach on February 1, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP