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)) |
The 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))) |
The 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)) |
The 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)) |
The 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)) |
The 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.