Dictionary creation using list contents in Python


Changing the collection type from one type to another is a very frequent need in python. In this article we will see how we create a dictionary when multiple lists are given. The challenge is to be able to combine all these lists to create one dictionary accommodating all these values in a dictionary key value format.

With zip

The zip function can be used to combine the values of different lists as shown below. In the below example we have taken three lists as input and combine them to form a single dictionary. One of the list supplies the keys for the dictionary and the other two lists hold the value filed for each of the key.

Example

 Live Demo

key_list = [1, 2,3]
day_list = ['Friday', 'Saturday','Sunday']
fruit_list = ['Apple','Banana','Grape']

# Given Lists
print("Given key list : " + str(key_list))
print("Given day list : " + str(day_list))
print("Given fruit list : " + str(fruit_list))


# Dictionary creation
res = {key: {'Day': day, 'Fruit': fruit} for key, day, fruit in
zip(key_list, day_list, fruit_list)}

# Result
print("The final dictionary : \n" ,res)

Output

Running the above code gives us the following result −

Given key list : [1, 2, 3]
Given day list : ['Friday', 'Saturday', 'Sunday']
Given fruit list : ['Apple', 'Banana', 'Grape']
The final dictionary :
{1: {'Day': 'Friday', 'Fruit': 'Apple'}, 2: {'Day': 'Saturday', 'Fruit': 'Banana'}, 3: {'Day': 'Sunday', 'Fruit': 'Grape'}}

With enumerate

The enumerate function adds a counter as the key of the enumerate object. So in our case we will supply the key_list as parameter to the

Example

 Live Demo

key_list = [1, 2,3]
day_list = ['Friday', 'Saturday','Sunday']
fruit_list = ['Apple','Banana','Grape']

# Given Lists
print("Given key list : " + str(key_list))
print("Given day list : " + str(day_list))
print("Given fruit list : " + str(fruit_list))


# Dictionary creation
res = {val : {"Day": day_list[key], "age": fruit_list[key]}
for key, val in enumerate(key_list)}

# Result
print("The final dictionary : \n" ,res)

Output

Running the above code gives us the following result −

Given key list : [1, 2, 3]
Given day list : ['Friday', 'Saturday', 'Sunday']
Given fruit list : ['Apple', 'Banana', 'Grape']
The final dictionary :
{1: {'Day': 'Friday', 'age': 'Apple'}, 2: {'Day': 'Saturday', 'age': 'Banana'}, 3: {'Day': 'Sunday', 'age': 'Grape'}}

Updated on: 04-May-2020

100 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements