"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Remove Duplicate Dictionaries from a List in Python?

How to Remove Duplicate Dictionaries from a List in Python?

Published on 2024-11-10
Browse:919

How to Remove Duplicate Dictionaries from a List in Python?

Removing Duplicates from a List of Dictionaries

In certain scenarios, it may be necessary to remove duplicate entries from a list of dictionaries. Duplicates occur when multiple dictionaries contain the same set of keys and values.

To achieve this, one approach involves creating a temporary dictionary where the keys are the unique identifiers of each dictionary. This filters out duplicates because dictionaries can only have unique keys. The values of the temporary dictionary represent the original dictionaries.

In Python, this can be accomplished using a dictionary comprehension:

temp = {v["id"]: v for v in L}
unique_dicts = list(temp.values())

Here's an example:

L = [
    {"id": 1, "name": "john", "age": 34},
    {"id": 1, "name": "john", "age": 34},
    {"id": 2, "name": "hanna", "age": 30},
]

temp = {v["id"]: v for v in L}
unique_dicts = list(temp.values())

print(unique_dicts)

This will output:

[{'id': 1, 'name': 'john', 'age': 34}, {'id': 2, 'name': 'hanna', 'age': 30}]

As you can see, the duplicate dictionary has been removed, resulting in a list of unique dictionaries.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3