This is a Python Program to map two lists into a dictionary.
The program takes two lists and maps two lists into a dictionary.
1. Declare two empty lists and initialize them to an empty list.
3. Consider a for loop to accept values for the two lists.
4. Take the number of elements in the list and store it in a variable.
5. Accept the values into the list using another for loop and insert into the list.
6. Repeat 4 and 5 for the values list also.
7. Zip the two lists and use dict() to convert it into a dictionary.
8. Print the dictionary.
9. Exit.
Here is source code of the Python Program to map two lists into a dictionary. The program output is also shown below.
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)
1. User must enter the number of elements in the list and store it in a variable.
2. User must enter the values to the same number of elements into the list.
3. 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.
4. The same of 2 and 3 is done for the second values list also.
5. The two lists are merged together using the zip() function.
6. The zipped lists are then merged to form a dictionary using dict().
7. The dictionary formed from the two lists is then printed.
Case 1: Enter number of elements for dictionary:3 For keys: Enter element1:1 Enter element2:2 Enter element3:3 For values: Enter element1:1 Enter element2:4 Enter element3:9 The dictionary is: {1: 1, 2: 4, 3: 9} Case 2: Enter number of elements for dictionary:2 For keys: Enter element1:23 Enter element2:46 For values: Enter element1:69 Enter element2:138 The dictionary is: {46: 138, 23: 69}
Sanfoundry Global Education & Learning Series – Python Programs.
To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.
- Practice Programming MCQs
- Check Information Technology Books
- Apply for Python Internship
- Check Python Books
- Apply for Programming Internship