by BehindJava
Write a program to Map Two Lists into a Dictionary in Python
In this tutorial we are going to learn about mapping Two Lists into a Dictionary in Python.
Python Program to Map Two Lists into a Dictionary
keys=[]
values=[]
n=int(input("Enter number of elements for dictionary:"))
print("For keys:")
for x in range(0,n):
element=int(input("Enter element" + str(x+1) + ":"))
keys.append(element)
print("For values:")
for x in range(0,n):
element=int(input("Enter element" + str(x+1) + ":"))
values.append(element)
d=dict(zip(keys,values))
print("The dictionary is:")
print(d)
Explanation
- User must enter the number of elements in the list and store it in a variable.
- User must enter the values to the same number of elements into the list.
- The append function obtains each element from the user and adds the same to the end of the list as many times as the number of elements taken.
- The same of 2 and 3 is done for the second values list also.
- The two lists are merged together using the zip() function.
- The zipped lists are then merged to form a dictionary using dict().
- The dictionary formed from the two lists is then printed.