Python Program - Convert Two Lists Into a Dictionary

htt‮p‬s://www.theitroad.com

Here's a Python program to convert two lists into a dictionary:

keys = ['a', 'b', 'c', 'd']
values = [1, 2, 3, 4]

# Using the zip() function to combine two lists into a dictionary
my_dict = dict(zip(keys, values))

print(my_dict)

Output:

{'a': 1, 'b': 2, 'c': 3, 'd': 4}

In this program, we have two lists keys and values which we want to convert into a dictionary. We use the zip() function to combine the two lists and create a list of key-value pairs. We then pass this list to the dict() constructor to create the final dictionary.

The zip() function takes two or more lists as input and returns an iterator that aggregates the elements of each list. The first item of the first list is paired with the first item of the second list, and so on, until all the items are paired. If the lists are of unequal length, zip() returns an iterator with the length of the shortest list.