Python | Grouping dictionary keys by value
While performing computations over dictionary, we can come across a problem in which we might have to perform the task of grouping keys according to value, i.e create a list of keys, it is value of. This can other in cases of organising data in case of machine learning. Let’s discuss certain way in which this task can be performed.
Method : Using sorted() + items() + defaultdict()
This task can be performed by combining the tasks which can be done by above functions. The defaultdict() is used to create a dictionary initialized with lists, items() gets the key-value pair and grouping is helped by sorted().
# Python3 code to demonstrate working of # Grouping dictionary keys by value # Using sorted() + items() + defaultdict() from collections import defaultdict # Initialize dictionary test_dict = {'gfg' : 1, 'is' : 2, 'best' : 1, 'for' : 3, 'CS' : 2} # printing original dictionary print("The original dictionary : " + str(test_dict)) # Using sorted() + items() + defaultdict() # Grouping dictionary keys by value res = defaultdict(list) for key, val in sorted(test_dict.items()): res[val].append(key) # printing result print("Grouped dictionary is : " + str(dict(res))) |
The original dictionary : {‘is’: 2, ‘for’: 3, ‘gfg’: 1, ‘CS’: 2, ‘best’: 1}
Grouped dictionary is : {1: [‘best’, ‘gfg’], 2: [‘CS’, ‘is’], 3: [‘for’]}
Recommended Posts:
- Python | Grouping list values into dictionary
- Python | Add new keys to a dictionary
- Python | Count keys with particular value in dictionary
- Python Dictionary | keys() method
- Python | Get dictionary keys as a list
- Python | Get total keys in dictionary
- Python | Get the number of keys with given value N in dictionary
- Python | Minimum value keys in Dictionary
- Python | Add keys to nested dictionary
- Python | Get all tuple keys from dictionary
- Python dictionary with keys having multiple inputs
- Python | Remove spaces from dictionary keys
- Python | Remove multiple keys from dictionary
- Python | Unpacking dictionary keys into tuple
- Python | Sort dictionary keys to 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.



