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()):
# printing result 
print("Grouped dictionary is : " + str(dict(res)))


Output :

The original dictionary : {‘is’: 2, ‘for’: 3, ‘gfg’: 1, ‘CS’: 2, ‘best’: 1}
Grouped dictionary is : {1: [‘best’, ‘gfg’], 2: [‘CS’, ‘is’], 3: [‘for’]}


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to 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.