Python - Group single item dictionaries into List values
Last Updated :
21 Apr, 2023
Given a List of single-item dictionaries, group them into dictionary value lists according to similar values.
Input : [{"Gfg" : 3}, {"is": 8}, {"Gfg": 18}, {"Best": 33}]
Output : {'Gfg': [3, 18], 'is': [8], 'Best': [33]}
Explanation : Each key converted to list values and dictionary.
Input : [{"Gfg" : 3}, {"Gfg": 8}, {"Gfg": 18}, {"Best": 33}]
Output : {'Gfg': [3, 18, 8], 'Best': [33]} E
Explanation : Each key converted to list values and dictionary.
Method #1 : Using setdefault() + loop
This is brute way in which this task can be performed. In this, we use to loop through all the dictionary values and setdefault() is used to assign common key its corresponding grouped value lists.
Python3
# Python3 code to demonstrate working of
# Group single item dictionaries into List values
# Using setdefault() + loop
# initializing lists
test_list = [{"Gfg" : 3}, {"is": 8}, {"Best": 10}, {"Gfg": 18}, {"Best": 33}]
# printing original list
print("The original list : " + str(test_list))
res = {}
# using loop to loop through each dictionary
for idx in test_list:
# items() to extract item
for key, val in idx.items():
# setdefault performs task of setting empty list value as default
res.setdefault(key, []).append(val)
# printing result
print("The constructed dictionary : " + str(res))
OutputThe original list : [{'Gfg': 3}, {'is': 8}, {'Best': 10}, {'Gfg': 18}, {'Best': 33}]
The constructed dictionary : {'Gfg': [3, 18], 'is': [8], 'Best': [10, 33]}
Time complexity: O(n * m), where n is the number of dictionaries in the list and m is the maximum number of items in a single dictionary.
Auxiliary Space: O(m), where m is the total number of keys in the grouped dictionary. The grouped dictionary (res) stores the values for each key, so the space complexity is proportional to the number of unique keys in the original list.
Method #2 : Using defaultdict() + * operator + loop
This is yet another way in which this task can be performed. In this, we use defaultdict() for empty list initialization. The * operator is used to unpack the dictionary item and loop is used to loop through dictionaries.
Python3
# Python3 code to demonstrate working of
# Group single item dictionaries into List values
# Using defaultdict() + * operator + loop
from collections import defaultdict
# initializing lists
test_list = [{"Gfg" : 3}, {"is": 8}, {"Best": 10}, {"Gfg": 18}, {"Best": 33}]
# printing original list
print("The original list : " + str(test_list))
res = defaultdict(list)
for ele in test_list:
# using * operator to unpack
# reducing one loop
key, val = tuple(*ele.items())
res[key].append(val)
# printing result
print("The constructed dictionary : " + str(dict(res)))
OutputThe original list : [{'Gfg': 3}, {'is': 8}, {'Best': 10}, {'Gfg': 18}, {'Best': 33}]
The constructed dictionary : {'Gfg': [3, 18], 'is': [8], 'Best': [10, 33]}
Time complexity: O(n), where n is the number of dictionaries in the test_list.
Auxiliary space: O(n), as we are storing the dictionaries in a defaultdict and each key-value pair takes up a constant amount of space.
Method #3 : Using extend(),keys(),list() and set() methods
Python3
# Python3 code to demonstrate working of
# Group single item dictionaries into List values
# initializing lists
test_list = [{"Gfg" : 3}, {"is": 8}, {"Best": 10}, {"Gfg": 18}, {"Best": 33}]
# printing original list
print("The original list : " + str(test_list))
res = {}
x=[]
for i in test_list:
x.extend(list(i.keys()))
x=list(set(x))
for i in x:
p=[]
for j in test_list:
if i in j.keys():
p.append(j[i])
res[i]=p
# printing result
print("The constructed dictionary : " + str(res))
OutputThe original list : [{'Gfg': 3}, {'is': 8}, {'Best': 10}, {'Gfg': 18}, {'Best': 33}]
The constructed dictionary : {'Best': [10, 33], 'Gfg': [3, 18], 'is': [8]}
Time Complexity : O(N*N)
Auxiliary Space : O(N)
Method 4: Using itertools.groupby() + lambda function
This method sorts the list by keys first, which helps groupby() to group the dictionaries with the same keys together. It also uses a list comprehension to extract the values from the grouped dictionaries, which is faster than using a loop with setdefault() or defaultdict().
- Initialize the input list of dictionaries, test_list.
- Sort the input list by the keys of the dictionaries using the sorted() function and a lambda function to extract the keys.
- Use the groupby() function from itertools to group the dictionaries with the same keys together. The first argument to groupby() is the sorted list from step 2, and the second argument is a lambda function that extracts the key from each dictionary in the list.
- Iterate over the groups returned by groupby(). For each group, extract the values from the dictionaries using a list comprehension and store them in a list.
- Create a new dictionary res and store the list of values for each key in the dictionary.
- Return the resulting dictionary res.
Python3
# Python3 code to demonstrate working of
# Group single item dictionaries into List values
# Using itertools.groupby() + lambda function
from itertools import groupby
# initializing lists
test_list = [{"Gfg" : 3}, {"is": 8}, {"Best": 10}, {"Gfg": 18}, {"Best": 33}]
# printing original list
print("The original list : " + str(test_list))
# using groupby() and lambda function to group
# dictionaries with same keys together
res = {}
for key, group in groupby(sorted(test_list, key=lambda x: list(x.keys())[0]), lambda x: list(x.keys())[0]):
res[key] = [val for d in group for val in d.values()]
# printing result
print("The constructed dictionary : " + str(res))
OutputThe original list : [{'Gfg': 3}, {'is': 8}, {'Best': 10}, {'Gfg': 18}, {'Best': 33}]
The constructed dictionary : {'Best': [10, 33], 'Gfg': [3, 18], 'is': [8]}
Time complexity: O(n log n) due to the sorting operation, where n is the number of dictionaries in the input list. The groupby() function and the list comprehension both have a linear time complexity of O(n).
Auxiliary space: O(n) for the resulting dictionary, where n is the number of unique keys in the input list.
Method 5: Using list comprehension and dictionary comprehension
Step-by-step approach:
- Use a list comprehension to extract all the keys from the input list of dictionaries.
- Use the set function to get the unique keys in the list.
- Use a dictionary comprehension to create the output dictionary, where each key is associated with a list of values from the input list of dictionaries that have that key.
- Print the result
Python3
# initializing lists
test_list = [{"Gfg" : 3}, {"is": 8}, {"Best": 10}, {"Gfg": 18}, {"Best": 33}]
# using list comprehension to extract keys
keys = list(set(key for d in test_list for key in d))
# using dictionary comprehension to group dictionaries into lists
res = {key: [d[key] for d in test_list if key in d] for key in keys}
# printing result
print("The constructed dictionary : " + str(res))
OutputThe constructed dictionary : {'is': [8], 'Gfg': [3, 18], 'Best': [10, 33]}
Time complexity: O(n*k), where n is the number of dictionaries in the input list and k is the average number of keys in each dictionary.
Auxiliary space: O(n*k) space to store the output dictionary, where n is the number of dictionaries in the input list and k is the average number of keys in each dictionary.
Similar Reads
Python - Group Similar items to Dictionary Values List
We are given a list of items and our task is to group similar elements together as dictionary values. The keys will be the unique items and their values will be lists containing all occurrences of that item. For example, given ['apple', 'banana', 'apple', 'orange', 'banana'], the output should be: {
2 min read
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
Dictionary items in value range in Python
In this article, we will explore different methods to extract dictionary items within a specific value range. The simplest approach involves using a loop.Using LoopThe idea is to iterate through dictionary using loop (for loop) and check each value against the given range and storing matching items
2 min read
Python - Group similar value list to dictionary
Sometimes, while working with Python list, we can have a problem in which we need to group similar value lists indices to values into a dictionary. This can have a good application in domains in which we need grouped dictionary as output for pair of lists. Lets discuss certain ways in which this tas
6 min read
Python | Segregating key's value in list of dictionaries
While working with dictionaries, we may encounter problems in which we need to segregate all the similar keys' values together. This kind of problem can occur in web development domain while working with databases. Let's discuss certain ways in which this problem can be solved. Method #1: Using gene
6 min read
Get Values from Dictionary Using For Loop - Python
In Python, dictionaries store data as key-value pairs and we are given a dictionary. Our task is to extract its values using a for loop, this approach allows us to iterate through the dictionary efficiently and retrieve only the values. For example, given d = {'a': 1, 'b': 2, 'c': 3}, we should extr
2 min read
Python - Summation Grouping in Dictionary List
Sometimes, while working with Python Dictionaries, we can have a problem in which we need to perform the grouping of dictionaries according to specific key, and perform summation of certain keys while grouping similar key's value. This is s peculiar problem but can have applications in domains such
5 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
Inverse Dictionary Values List - Python
We are given a dictionary and the task is to create a new dictionary where each element of the value lists becomes a key and the original keys are grouped as lists of values for these new keys.For example: dict = {1: [2, 3], 2: [3], 3: [1]} then output will be {2: [1], 3: [1, 2], 1: [3]}Using defaul
2 min read
Python | Group tuple into list based on value
Sometimes, while working with Python tuples, we can have a problem in which we need to group tuple elements to nested list on basis of values allotted to it. This can be useful in many grouping applications. Let's discuss certain ways in which this task can be performed. Method #1 : Using itemgetter
6 min read