Skip to content
Related Articles

Related Articles

Python – Convert Lists to Nested Dictionary
  • Last Updated : 14 May, 2020
GeeksforGeeks - Summer Carnival Banner

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}}]

 

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.

My Personal Notes arrow_drop_up
Recommended Articles
Page :