Python | Remove duplicate dictionaries from nested dictionary
Given a nested dictionary, the task is to remove duplicate dictionaries from the dictionary. Given below are few methods to complete the given task.
Method #1: Using Naive Method
# Python code to demonstrate # for removing duplicate values from dictionary # initialising dictionary ini_dict = {'a':{'b':1, 'c':2}, 'b':{'b':1, 'c':2}, 'c':{'a':2, 'b':3}, 'd':{'a':2, 'b':7}} # printing initial_dictionary print ("initial dictionary", str(ini_dict)) # code to remove duplicates result = {} for key, value in ini_dict.items(): if value not in result.values(): result[key] = value # printing result print ("result", str(result)) |
initial dictionary {‘c’: {‘a’: 2, ‘b’: 3}, ‘d’: {‘a’: 2, ‘b’: 7}, ‘a’: {‘c’: 2, ‘b’: 1}, ‘b’: {‘c’: 2, ‘b’: 1}}
result {‘c’: {‘a’: 2, ‘b’: 3}, ‘d’: {‘a’: 2, ‘b’: 7}, ‘a’: {‘c’: 2, ‘b’: 1}}
Method #2: Using sorted and set
# Python code to demonstrate # for removing duplicate values from dictionary # initialising dictionary ini_dict = {'a':{'b':1, 'c':2}, 'b':{'b':1, 'c':2}, 'c':{'a':2, 'b':3}, 'd':{'a':2, 'b':7}} # printing initial_dictionary print ("initial dictionary", str(ini_dict)) # code to remove duplicates keep = set({repr(sorted(value.items())):key for key, value in ini_dict.items()}.values()) for key in list(ini_dict): if key not in keep: del ini_dict[key] # printing result print ("result", str(ini_dict)) |
initial dictionary {‘a’: {‘b’: 1, ‘c’: 2}, ‘b’: {‘b’: 1, ‘c’: 2}, ‘c’: {‘a’: 2, ‘b’: 3}, ‘d’: {‘a’: 2, ‘b’: 7}}
result {‘b’: {‘b’: 1, ‘c’: 2}, ‘c’: {‘a’: 2, ‘b’: 3}, ‘d’: {‘a’: 2, ‘b’: 7}}
Recommended Posts:
- Python | Convert nested dictionary into flattened dictionary
- Python | Convert flattened dictionary into nested dictionary
- Python | Removing dictionary from list of dictionaries
- Python | Split dictionary of lists to list of dictionaries
- Python | Nested Dictionary
- Python | Sum values for each key in nested dictionary
- Python | Add keys to nested dictionary
- Python | Sort nested dictionary by key
- Python | Safe access nested dictionary keys
- Python | Find keys with duplicate values in dictionary
- Python | Convert list of nested dictionary into Pandas dataframe
- Python | Remove all occurrences in nested list
- Python | Remove duplicates from nested list
- Python | Remove all duplicates and permutations in nested list
- Python | Remove unordered duplicate elements from a list
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



