Create a dictionary from two lists in python :
In this python programming tutorial, we will learn how to create a dictionary from two different user input lists. Our program will ask the user to enter the values for both lists and then it will create one dictionary by taking the values. Values of the first list will be the key of the dictionary and corresponding values of the second list will be the value of the dictionary. Let’s take a look at the program :
Python program :
You can download the code from here.
The commented numbers in the above program denote the step number below :
1. Create two empty lists first_list and second_list to store the values for the keys and values of the dictionary.
2. Ask the user to enter the size of both the lists. Read and store them in first_list_size and second_list_size variables.
3. Run one for loop. Take the values for the first list from the user and store them in first_list list.
4. Similarly, using one for loop, read and store the values for the second list in second_list variable.
5. Print out both lists to the user.
6. Using zip(), create one list of pairs from the lists. Then using dict(), convert that list of pairs to a dictionary.
7. Print out the created dictionary.
Sample Output :
Zipping is the easiest way to convert two lists to a dictionary. The first example we have shown above is a simple one, but the second and third examples are a little bit different. Both have different numbers of items in the lists. You can see that the final dictionary doesn’t contain all items.zip() ignores the items of a list if it doesn’t have anything corresponding in the other list. Go through the example and drop a comment below if you have any queries.
You might also like :
- Python 3 Ordered Dictionary (OrderedDict) with example
- How to delete a key from a python dictionary
- Python program to concatenate two dictionaries
- Python program to print all even numbers in a range
- Python program to count the total number of lines in a file
- Logical operators in Python : Explanation with example