Python | Dictionary creation using list contents
Sometimes we need to handle the data coming in the list format and convert list into dictionary format. This particular problem is quite common while we deal with Machine Learning to give further inputs in changed formats. Let’s discuss certain ways in which this inter conversion happens.
Method #1 : Using dictionary comprehension + zip()
In this method, we use dictionary comprehension to perform the iteration and logic part, the binding of all the lists into one dictionary and with associated keys is done by zip function.
# Python3 code to demonstrate# Dictionary creation using list contents# using Dictionary comprehension + zip() # initializing listkeys_list = ["key1", "key2"]nested_name = ["Manjeet", "Nikhil"]nested_age = [22, 21] # printing original listsprint("The original key list : " + str(keys_list))print("The original nested name list : " + str(nested_name))print("The original nested age list : " + str(nested_age)) # using Dictionary comprehension + zip()# Dictionary creation using list contentsres = {key: {'name': name, 'age': age} for key, name, age in zip(keys_list, nested_name, nested_age)} # print resultprint("The dictionary after construction : " + str(res)) |
The original key list : [‘key1’, ‘key2’]
The original nested name list : [‘Manjeet’, ‘Nikhil’]
The original nested age list : [22, 21]
The dictionary after construction : {‘key1’: {‘age’: 22, ‘name’: ‘Manjeet’}, ‘key2’: {‘age’: 21, ‘name’: ‘Nikhil’}}
Method #2 : Using dictionary comprehension + enumerate()
The similar task can be performed using enumerate function that was performed by the zip function. The dictionary comprehension performs the task similar as above.
# Python3 code to demonstrate# Dictionary creation using list contents# using dictionary comprehension + enumerate() # initializing listkeys_list = ["key1", "key2"]nested_name = ["Manjeet", "Nikhil"]nested_age = [22, 21] # printing original listsprint("The original key list : " + str(keys_list))print("The original nested name list : " + str(nested_name))print("The original nested age list : " + str(nested_age)) # using dictionary comprehension + enumerate()# Dictionary creation using list contentsres = {val : {"name": nested_name[key], "age": nested_age[key]} for key, val in enumerate(keys_list)} # print resultprint("The dictionary after construction : " + str(res)) |
The original key list : [‘key1’, ‘key2’]
The original nested name list : [‘Manjeet’, ‘Nikhil’]
The original nested age list : [22, 21]
The dictionary after construction : {‘key1’: {‘age’: 22, ‘name’: ‘Manjeet’}, ‘key2’: {‘age’: 21, ‘name’: ‘Nikhil’}}



