Python Remove Duplicates from List of Dicts

Language:
Python
6 views
0 favorites
2 hours ago

Code Implementation

Python
def unique_dicts(data, key):
    seen = set()
    result = []
    for d in data:
        if d[key] not in seen:
            seen.add(d[key])
            result.append(d)
    return result

# Usage
data = [
    {"id": 1, "name": "Alice"},
    {"id": 1, "name": "Alice"},
    {"id": 2, "name": "Bob"}
]
print(unique_dicts(data, "id"))

Remove duplicates from a list of dictionaries based on a specific key in the dictionaries.

#dict#deduplicate

Snippet Description

  • Use a set to record the keys that have been seen
  • Ensure that only the first record with the same key is retained in the result
  • Often used to deduplicate database query results

Comments

Loading...