Python – Unnest single Key Nested Dictionary List
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}Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
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 code to demonstrate working of # Unnest single Key Nested Dictionary List# Using loop + items() # initializing listtest_list = [{'gfg' : {'data' : 1}}, {'is' : {'data' : 5}}, {'best' : {'data' : 4}}] # printing original listprint("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}
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 code to demonstrate working of # Unnest single Key Nested Dictionary List# Using list comprehension # initializing listtest_list = [{'gfg' : {'data' : 1}}, {'is' : {'data' : 5}}, {'best' : {'data' : 4}}] # printing original listprint("The original list is : " + str(test_list)) # initializing key data_key = 'data' # Unnest single Key Nested Dictionary List# Using list comprehensionres = {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}


