Python – Convert Lists to Nested Dictionary

Sometimes, while working with Python dictionaries, we can have a problem in which we need to convert list to nestings, i.e each list values representing new nested level. This kind of problem can have application in many domains including web development. Lets discuss certain way in which this task can be performed.

Method : Using zip() + list comprehension
The combination of above functions can be combined to perform this task. In this, we iterate for zipped list and render the nested dictionaries using list comprehension.





# Python3 code to demonstrate working of 
# Convert Lists to Nestings Dictionary
# Using list comprehension + zip()
# initializing list
test_list1 = ["gfg", 'is', 'best']
test_list2 = ['ratings', 'price', 'score']
test_list3 = [5, 6, 7]
# printing original list
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
print("The original list 3 is : " + str(test_list3))
# Convert Lists to Nestings Dictionary
# Using list comprehension + zip()
res = [{a: {b: c}} for (a, b, c) in zip(test_list1, test_list2, test_list3)]
# printing result 
print("The constructed dictionary : " + str(res)) 


Output :

The original list 1 is : ['gfg', 'is', 'best']
The original list 2 is : ['ratings', 'price', 'score']
The original list 3 is : [5, 6, 7]
The constructed dictionary : [{'gfg': {'ratings': 5}}, {'is': {'price': 6}}, {'best': {'score': 7}}]


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.