Python | Grouping dictionary keys by value
Last Updated :
10 May, 2023
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 1: 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
# 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)))
Output:
The original dictionary : {'gfg': 1, 'is': 2, 'best': 1, 'for': 3, 'CS': 2}
Grouped dictionary is : {2: ['CS', 'is'], 1: ['best', 'gfg'], 3: ['for']}
Time Complexity: O(n*n), where n is the length of the list test_dict
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list
Method 2:
Additionally, This task can also be performed without using any module.
So the logic here is:
We can check if the keys are present or not
1. No, then we can create key res[v] = [i]
2. Yes, we can append value on the key res[v] + [i]
Python3
d_input = {'Input.txt': 'Randy', 'Code.py': 'Stan', 'Output.txt': 'Randy'}
res = {}
for i, v in d_input.items():
res[v] = [i] if v not in res.keys() else res[v] + [i]
print(res)
Output:
{'Randy': ['Input.txt', 'Output.txt'], 'Stan': ['Code.py']}
Method 3: Using itertools.groupby()
Itertools.groupby() is a tool used to group elements based on a key. The key is a function that is applied to each element in order to determine its group. In this case, we can use the same dictionary.items() method to provide the key to the itertools.groupby()
Python3
# Python3 code to demonstrate working of
# Grouping dictionary keys by value
# Using itertools.groupby()
from itertools import groupby
# 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 itertools.groupby()
# Grouping dictionary keys by value
res = {i: [j[0] for j in j] for i, j in groupby(sorted(test_dict.items(), key = lambda x : x[1]), lambda x : x[1])}
# printing result
print("Grouped dictionary is : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy
OutputThe original dictionary : {'gfg': 1, 'is': 2, 'best': 1, 'for': 3, 'CS': 2}
Grouped dictionary is : {1: ['gfg', 'best'], 2: ['is', 'CS'], 3: ['for']}
Time Complexity: O(n log n)
Auxiliary Space: O(n)
Method 4 : Using a loop
Step-by-step approach:
- Initialize an empty dictionary to store the grouped keys.
- Iterate through the items of the original dictionary.
- For each item, check if the value is already a key in the grouped dictionary.
- If it is not, add the value as a key and initialize its value as a list containing the key from the original dictionary.
- If it is already a key, append the key from the original dictionary to the list of values associated with that key.
- Return the grouped dictionary.
Python3
# Python3 code to demonstrate working of
# Grouping dictionary keys by value
# Using a loop
# 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 a loop
# Grouping dictionary keys by value
grouped_dict = {}
for key, value in test_dict.items():
if value not in grouped_dict:
grouped_dict[value] = [key]
else:
grouped_dict[value].append(key)
# printing result
print("Grouped dictionary is : " + str(grouped_dict))
OutputThe original dictionary : {'gfg': 1, 'is': 2, 'best': 1, 'for': 3, 'CS': 2}
Grouped dictionary is : {1: ['gfg', 'best'], 2: ['is', 'CS'], 3: ['for']}
The time complexity of this method is O(n), where n is the number of items in the dictionary.
The auxiliary space complexity is also O(n), because the grouped dictionary may contain all the keys and values from the original dictionary.
Similar Reads
Python | Grouping list values into dictionary
Sometimes, while working with data, we can be encountered a situation in which we have a list of lists and we need to group its 2nd index with the common initial element in lists. Let's discuss ways in which this problem can be solved. Method 1: Using defaultdict() + loop + dict() The defaultdict ca
7 min read
Python - Group Similar keys in dictionary
Sometimes while working with dictionary data, we can have problems in which we need to perform grouping based on the substring of keys and reform the data grouped on similar keys. This can have application in data preprocessing. Let us discuss certain ways in which this task can be performed. Method
5 min read
Minimum Value Keys in Dictionary - Python
We are given a dictionary and need to find all the keys that have the minimum value among all key-value pairs. The goal is to identify the smallest value in the dictionary and then collect every key that matches it. For example, in {'a': 3, 'b': 1, 'c': 2, 'd': 1}, the minimum value is 1, so the res
4 min read
Python Update Dictionary Value by Key
A Dictionary in Python is an unordered collection of key-value pairs. Each key must be unique, and you can use various data types for both keys and values. Dictionaries are enclosed in curly braces {}, and the key-value pairs are separated by colons. Python dictionaries are mutable, meaning you can
3 min read
Python Iterate Dictionary Key, Value
In Python, a Dictionary is a data structure that stores the data in the form of key-value pairs. It is a mutable (which means once created we modify or update its value later on) and unordered data structure in Python. There is a thing to keep in mind while creating a dictionary every key in the dic
3 min read
Get Total Keys in Dictionary - Python
We are given a dictionary and our task is to count the total number of keys in it. For example, consider the dictionary: data = {"a": 1, "b": 2, "c": 3, "d": 4} then the output will be 4 as the total number of keys in this dictionary is 4.Using len() with dictThe simplest way to count the total numb
2 min read
Sort a Nested Dictionary by Value in Python
Sorting a nested dictionary in Python involves understanding its structure, defining sorting criteria, and utilizing the `sorted()` function or `.sort()` method with a custom sorting function, often a lambda. This process is essential for organizing complex, hierarchical data efficiently. Mastery of
3 min read
Python - Sort Dictionary by Values and Keys
Given a dictionary, sort according to descended values, if similar values, then by keys lexicographically. Input : test_dict = {"gfg" : 1, "is" : 1, "best" : 1, "for" : 1, "geeks" : 1} Output : {"best" : 1, "is" : 1, "for" : 1, "geeks" : 1, "gfg" : 1} Explanation : All values are equal, hence lexico
3 min read
Python Remove Item from Dictionary by Value
We are given a dictionary and our task is to remove key-value pairs where the value matches a specified target. This can be done using various approaches, such as dictionary comprehension or iterating through the dictionary. For example: d = {"a": 10, "b": 20, "c": 10, "d": 30} and we have to remove
3 min read
Python - Unique Values of Key in Dictionary
We are given a list of dictionaries and our task is to extract all the unique values associated with a given key. For example, consider: data = [ {"name": "Aryan", "age": 25}, {"name": "Harsh", "age": 30}, {"name": "Kunal", "age": 22}, {"name": "Aryan", "age": 27}]key = "name"Then, the unique values
4 min read