![]() |
VOOZH | about |
We are given a nested dictionary we need to remove the duplicate dictionaries from the nested dictionary. For example we are given a nested dictionary d = {'key1': [{'a': 1}, {'b': 2}, {'a': 1}], 'key2': [{'x': 3}, {'y': 4}]} we need to remove the duplicate dictionary from this dictionary so output should be {'key1': [{'a': 1}, {'b': 2}], 'key2': [{'y': 4}, {'x': 3}]}. We can use sets , list comprehension for this.
A simple way is to convert list of dictionaries to a set of frozen sets (since sets cannot contain duplicate elements) and then back to a list.
{'key1': [{'b': 2}, {'a': 1}], 'key2': [{'y': 4}, {'x': 3}]}
Explanation:
We can manually track seen dictionaries using a set to avoid duplicates.
{'key1': [{'a': 1}, {'b': 2}], 'key2': [{'x': 3}, {'y': 4}]}
Explanation:
Code uses list comprehension and a set to remove duplicates from lists of dictionaries. It converts each dictionary to a frozenset to ensure uniqueness then iterates through list adding only unique dictionaries to a new list which is then used to update the original dictionary.
{'key1': [{'a': 1}, {'b': 2}], 'key2': [{'x': 3}, {'y': 4}]}
Explanation:
pandasIf we are working with large datasets we can use pandas to convert dictionaries into a DataFrame and remove duplicates easily.
{'key1': [{'a': 1.0, 'b': nan}, {'a': nan, 'b': 2.0}], 'key2': [{'x': 3.0, 'y': nan}, {'x': nan, 'y': 4.0}]}
Explanation: