Python - Unnest single Key Nested Dictionary List
Last Updated :
09 Apr, 2023
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, 'geeks' : 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))
Output :
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))
Output :
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))
OutputThe 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))
OutputThe 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)
OutputThe 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))
OutputThe constructed Dictionary list : {'gfg': 1, 'is': 5, 'best': 4}
Time Complexity: O(n)
Auxiliary Space: O(n)
Similar Reads
Create Nested Dictionary using given List - Python
The task of creating a nested dictionary in Python involves pairing the elements of a list with the key-value pairs from a dictionary. Each key from the list will map to a dictionary containing a corresponding key-value pair from the original dictionary. For example, given the dictionary a = {'Gfg':
3 min read
Convert List to Single Dictionary Key - Value list - Python
We are given a list and a element K, our aim is to transform the given list into a dictionary where the specified element (Kth element) becomes the key and the rest of the elements form the value list. For example: if the given list is: [6, 5, 3, 2] and K = 1 then the output will be {5: [6, 3, 2]}.U
4 min read
Python - K list Nested Dictionary Mesh
Given 2 lists, create nested mesh with constant List. Input : test_list1 = [4, 6], test_list2 = [2, 7], K = [] Output : {4: {2: [], 7: []}, 6: {2: [], 7: []}} Explanation : Nested dictionary initialized with []. Input : test_list1 = [4], test_list2 = [2], K = [1] Output : {4: {2: [1]}} Explanation :
2 min read
Python | Sort dictionary keys to list
Sometimes, we wish to flatten the dictionary into list, the simple flattening is relatively easier, but when we wish to align keys and values in sorted way, i.e sorted by value, then it becomes quite a complex problem. Let's discuss certain ways in which this task can be performed. Method #1 : Using
4 min read
Three Level Nested Dictionary Python
In Python, a dictionary is a built-in data type used to store data in key-value pairs. Defined with curly braces `{}`, each pair is separated by a colon `:`. This allows for efficient representation and easy access to data, making it a versatile tool for organizing information. What is 3 Level Neste
4 min read
Convert Nested Dictionary to List in Python
In this article, weâll explore several methods to Convert Nested Dictionaries to a List in Python. List comprehension is the fastest and most concise way to convert a nested dictionary into a list.Pythona = { "a": {"x": 1, "y": 2}, "b": {"x": 3, "y": 4}, } # Convert nested dictionary to a list of li
3 min read
Python - Print dictionary of list values
In this article, we will explore various ways on How to Print Dictionary in Python of list values. A dictionary of list values means a dictionary contains values as a list of dictionaries in Python. Example: {'key1': [{'key1': value,......,'key n': value}........{'key1': value,......,'key n': value}
4 min read
Python Get All Values from Nested Dictionary
In this article, we will learn how we can Get all Values from Nested Dictionary in Python Programming. A nested Dictionary in Python is a dictionary that contains another dictionary as its values. Using this, we can create a nested structure where each of the key-value pairs is in the outer dictiona
5 min read
Python Print Dictionary Keys and Values
When working with dictionaries, it's essential to be able to print their keys and values for better understanding and debugging. In this article, we'll explore different methods to Print Dictionary Keys and Values.Example: Using print() MethodPythonmy_dict = {'a': 1, 'b': 2, 'c': 3} print("Keys:", l
2 min read
Python - Remove K valued key from Nested Dictionary
We are given a nested dictionary we need to remove K valued key. For example, we are given a nested dictionary d = { "a": 1, "b": {"c": 2,"d": {"e": 3,"f": 1},"g": 1},"h": [1, {"i": 1, "j": 4}]} we need to remove K valued key ( in our case we took k value as 1 ) from it so that the output should be
3 min read