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
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 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 - 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
Get Python Dictionary Values as List - Python We are given a dictionary where the values are lists and our task is to retrieve all the values as a single flattened list. For example, given the dictionary: d = {"a": [1, 2], "b": [3, 4], "c": [5]} the expected output is: [1, 2, 3, 4, 5]Using itertools.chain()itertools.chain() function efficiently
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 - Create a Dictionary using List with None Values The task of creating a dictionary from a list of keys in Python involves transforming a list of elements into a dictionary where each element becomes a key. Each key is typically assigned a default value, such as None, which can be updated later. For example, if we have a list like ["A", "B", "C"],
3 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
Get List of Values From Dictionary - Python We are given a dictionary and our task is to extract all the values from it and store them in a list. For example, if the dictionary is d = {'a': 1, 'b': 2, 'c': 3}, then the output would be [1, 2, 3].Using dict.values()We can use dict.values() along with the list() function to get the list. Here, t
2 min read