Python Program to Convert Lists into a Dictionary

In this sample program, you will learn how to convert lists to a Python dictionary and show it using the print() function.

To understand this demo program, you should have the basic Python programming knowledge.

However, here we’ll use the following steps to convert lists into a dictionary.

  1. Define a pair of lists: one for the keys and one for the values.
  2. Set the lists as empty that means they should not have any elements.
  3. Then the program asks for following three types of inputs from the user.
  4. The first, it gets the no. of elements that you want in the list.
  5. After that, it uses a for loop which asks the user to supply inputs and get them added to the list of keys.
  6. Next is another for loop which receives values from the end-user and keeps adding them to list of values in each iteration.
  7. Finally, we call the Zip() method to convert lists into a dictionary.
  8. Print the dictionary object.

Below is the sample code of the Python Program to convert lists into a dictionary using the Zip() method.

Python Program to Convert Lists into a Dictionary

You can use IDLE or any other Python IDE to create and execute the below program.

# Program to Convert Lists into a Dictionary

# Pair of lists for storing the keys and values
listOfkeys = []
listOfvalues = []

count = int(input("Input total no. of elements in the lists:"))
print("Capture input for the keys:")

for item in range(0, count):
    elt = int(input("Input item" + str(item + 1) + ":"))
    listOfkeys.append(elt)

print("Capture input for the values:")

for item in range(0, count):
    elt = int(input("Input item" + str(item + 1) + ":"))
    listOfvalues.append(elt)

di = dict(zip(listOfkeys, listOfvalues))
print("The dictionary after the merge:")
print(di)

The output of the above code is as follows.

Input total no. of elements in the lists:5
Capture input for the keys:
Input item1:1
Input item2:2
Input item3:3
Input item4:4
Input item5:5
Capture input for the values:
Input item1:11
Input item2:22
Input item3:33
Input item4:44
Input item5:55
The dictionary after the merge:
{1: 11, 2: 22, 3: 33, 4: 44, 5: 55}