Write a Python Program to Convert Two Lists Into a Dictionary

In Python, you can easily convert two lists into a dictionary using the built-in function zip().

The zip() function takes two lists as arguments and returns a list of tuples where each tuple contains elements from both lists, paired together in order.

You can then convert this list of tuples into a dictionary using the dict() constructor.

Here’s an example program that demonstrates how to convert two lists into a dictionary:

# define two lists
keys = ['a', 'b', 'c']
values = [1, 2, 3]

# use the zip() function to combine the two lists into a list of tuples
pairs = zip(keys, values)

# use the dict() constructor to create a dictionary from the list of tuples
dictionary = dict(pairs)

# print the resulting dictionary
print(dictionary)

Output:

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

In this example, we first define two lists keys and values containing some data.

We then use the zip() function to combine these two lists into a list of tuples pairs.

Finally, we use the dict() constructor to create a dictionary from the list of tuples, which we assign to the variable dictionary.

We then print the resulting dictionary to verify that it contains the expected key-value pairs.

Note that if the two lists are of different lengths, the resulting dictionary will only contain as many key-value pairs as there are elements in the shorter list.

If you need to handle lists of different lengths, you can use a loop to iterate over the shorter list and add each element to the dictionary one at a time.