Sometimes, while working with Python data, we can have a problem in which we need to perform unnesting of all the dictionaries which have single nesting of keys, i.e a single key and value and can easily be pointed to outer key directly. This kind of problem is common in domains requiring data optimization. Let’s discuss certain ways in which this task can be performed.
Input : test_list = [{‘gfg’ : {‘data’ : 1}}, {‘is’ : {‘data’ : 5, ‘Lazyroar’ : 7}}]
Output : {‘is’: 5, ‘gfg’: 1}Input : test_list = [{‘gfg’ : {‘data’ : ‘best’}}]
Output : {‘gfg’: ‘best’}
Method #1: Using loop + items() The combination of above methods can be used to solve this problem. In this, we iterate for the values in list, using loop and extract all dictionary items using items() and perform new dictionary creation using brute force method.
Python3
# Python3 code to demonstrate working of # Unnest single Key Nested Dictionary List # Using loop + items() # initializing list test_list = [{ 'gfg' : { 'data' : 1 }}, { 'is' : { 'data' : 5 }}, { 'best' : { 'data' : 4 }}] # printing original list print ("The original list is : " + str (test_list)) # initializing key data_key = 'data' # Unnest single Key Nested Dictionary List # Using loop + items() res = dict () for sub in test_list: for key, val in sub.items(): res[key] = sub[key][data_key] # printing result print ("The constructed Dictionary list : " + str (res)) |
The original list is : [{‘gfg’: {‘data’: 1}}, {‘is’: {‘data’: 5}}, {‘best’: {‘data’: 4}}] The constructed Dictionary list : {‘gfg’: 1, ‘best’: 4, ‘is’: 5}
Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(1).
Method #2 : Using list comprehension This is yet another way in which this task can be performed. In this, we perform solution in similar approach but in shorthand way using list comprehension.
Python3
# Python3 code to demonstrate working of # Unnest single Key Nested Dictionary List # Using list comprehension # initializing list test_list = [{ 'gfg' : { 'data' : 1 }}, { 'is' : { 'data' : 5 }}, { 'best' : { 'data' : 4 }}] # printing original list print ("The original list is : " + str (test_list)) # initializing key data_key = 'data' # Unnest single Key Nested Dictionary List # Using list comprehension res = {x : y[data_key] for idx in test_list for x, y in idx.items()} # printing result print ("The constructed Dictionary list : " + str (res)) |
The original list is : [{‘gfg’: {‘data’: 1}}, {‘is’: {‘data’: 5}}, {‘best’: {‘data’: 4}}] The constructed Dictionary list : {‘gfg’: 1, ‘best’: 4, ‘is’: 5}
Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(n), as a new dictionary is created with n key-value pairs.
Method #2 : Using list comprehension
This approach first uses the map() function to iterate over the list and applies a lambda expression to each element of the list. The lambda expression extracts the key and the value for the specified key ‘data‘ from the nested dictionary and creates a tuple of key-value pairs. Finally, the dict() function is used to convert the list of tuples into a dictionary.
Python3
# Python3 code to demonstrate working of # Unnest single Key Nested Dictionary List # Using map() + lambda expression # initializing list test_list = [{ 'gfg' : { 'data' : 1 }}, { 'is' : { 'data' : 5 }}, { 'best' : { 'data' : 4 }}] # printing original list print ( "The original list is : " + str (test_list)) # initializing key data_key = 'data' # Unnest single Key Nested Dictionary List # Using map() + lambda expression res = dict ( map ( lambda x: ( list (x.keys())[ 0 ], x[ list (x.keys())[ 0 ]][data_key]), test_list)) # printing result print ( "The constructed Dictionary list : " + str (res)) |
The original list is : [{'gfg': {'data': 1}}, {'is': {'data': 5}}, {'best': {'data': 4}}] The constructed Dictionary list : {'gfg': 1, 'is': 5, 'best': 4}
Time complexity: O(n), where n is the length of the input list test_list.
Auxiliary space: O(n), as it creates a new dictionary res of size n to store the unnested dictionary elements.
Method 3: Using the reduce() function from the functools module
The reduce() function is used to merge all the dictionaries in the list test_list into a single dictionary merged_dict. Then, a dictionary comprehension is used to extract the value of the data_key from each dictionary in merged_dict and create the final result dictionary res.
Python3
from functools import reduce test_list = [{ 'gfg' : { 'data' : 1 }}, { 'is' : { 'data' : 5 }}, { 'best' : { 'data' : 4 }}] data_key = 'data' merged_dict = reduce ( lambda x, y: { * * x, * * y}, test_list) res = {k: v[data_key] for k, v in merged_dict.items()} print ( "The constructed Dictionary list : " + str (res)) |
The constructed Dictionary list : {'gfg': 1, 'is': 5, 'best': 4}
The time complexity of this code is O(n), where n is the number of dictionaries in the input list test_list.
The space complexity is O(n), where n is the number of dictionaries in the input list test_list.
Method #5: Using dictionary comprehension
Step-by-step approach:
- Initialize a variable data_key with the value ‘data’.
- Use dictionary comprehension to unnest the nested dictionaries in test_list. The comprehension will iterate over each dictionary in test_list, get the key of the first item in the dictionary (which will be a string), and get the value associated with the data_key key within the nested dictionary. This will create a new dictionary where the keys are the strings in the original dictionaries, and the values are the values associated with the data_key key in the nested dictionaries.
- Assign the resulting dictionary to a new variable called res.
- Print the resulting dictionary using the print() function.
Python3
# Python3 code to demonstrate working of # Unnest single Key Nested Dictionary List # Using dictionary comprehension # initializing list test_list = [{ 'gfg' : { 'data' : 1 }}, { 'is' : { 'data' : 5 }}, { 'best' : { 'data' : 4 }}] # printing original list print ( "The original list is : " + str (test_list)) # initializing key data_key = 'data' # Unnest single Key Nested Dictionary List # Using dictionary comprehension res = { list (x.keys())[ 0 ]: x[ list (x.keys())[ 0 ]][data_key] for x in test_list} # printing result print ( "The constructed Dictionary list : " + str (res)) # Time Complexity: O(n) # Auxiliary Space: O(n) |
The original list is : [{'gfg': {'data': 1}}, {'is': {'data': 5}}, {'best': {'data': 4}}] The constructed Dictionary list : {'gfg': 1, 'is': 5, 'best': 4}
Time Complexity: O(n)
Auxiliary Space: O(n)
Method 6: Using map() function
Steps:
- Initialize the input list test_list.
- Initialize the key data_key.
- Use the map() function to iterate over each dictionary in the list and return a tuple of the form (key, value) where key is the only key in the dictionary and value is the value of the data_key key in the nested dictionary.
- Convert the result of map() to a dictionary using the dict() function.
- Print the resulting dictionary.
Python3
# initializing list test_list = [{ 'gfg' : { 'data' : 1 }}, { 'is' : { 'data' : 5 }}, { 'best' : { 'data' : 4 }}] # initializing key data_key = 'data' # Unnest single Key Nested Dictionary List # Using map() function res = dict ( map ( lambda x: ( list (x.keys())[ 0 ], x[ list (x.keys())[ 0 ]][data_key]), test_list)) # printing result print ( "The constructed Dictionary list : " + str (res)) |
The constructed Dictionary list : {'gfg': 1, 'is': 5, 'best': 4}
Time Complexity: O(n)
Auxiliary Space: O(n)