Duplication in a data collection can be a hindrance to efficient data processing. In Python programming, lists of dictionaries are commonly used to store tabular data. However, there may be instances where you need to remove duplicate dictionaries from such a list.
Consider the following list of dictionaries:
[ {'id': 1, 'name': 'john', 'age': 34}, {'id': 1, 'name': 'john', 'age': 34}, {'id': 2, 'name': 'hanna', 'age': 30}, ]
The goal is to obtain a list with only unique dictionaries, excluding the duplicates. To achieve this, we can employ a straightforward approach:
Creating a Temporary Dictionary with ID as Key
Extracting Unique Dictionaries from Values
Python Implementation
Here's how to implement this approach in Python:
def remove_duplicates_from_dicts(dict_list):
dict_id_mapping = {v['id']: v for v in dict_list}
return list(dict_id_mapping.values())
sample_list = [
{'id': 1, 'name': 'john', 'age': 34},
{'id': 1, 'name': 'john', 'age': 34},
{'id': 2, 'name': 'hanna', 'age': 30},
]
print(remove_duplicates_from_dicts(sample_list))
This code will produce the following output:
[{'id': 1, 'name': 'john', 'age': 34}, {'id': 2, 'name': 'hanna', 'age': 30}]
By employing this strategy, you can effectively remove duplicate dictionaries from a list and obtain a new list with only unique elements.
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