How to create a dictionary from two lists in Python?

Published on Aug. 22, 2023, 12:17 p.m.

To create a dictionary from two lists in Python, you can use a dictionary comprehension or the zip() function. Here are some examples:

Using a dictionary comprehension:

keys = ['key1', 'key2', 'key3']
values = [10, 45, 23]
my_dict = {keys[i]: values[i] for i in range(len(keys))}
print(my_dict)  # Output: {'key1': 10, 'key2': 45, 'key3': 23}

In this example, a dictionary comprehension is used to create a dictionary where the keys are taken from the keys list and the values from the values list. To iterate over both lists at the same time, range(len(keys)) is used to generate a sequence of indices that is passed to the dictionary comprehension.

Using the zip() function:

keys = ['key1', 'key2', 'key3']
values = [10, 45, 23]
my_dict = dict(zip(keys, values))
print(my_dict)  # Output: {'key1': 10, 'key2': 45, 'key3': 23}

In this example, the zip() function is used to create pairs of keys and values from the keys and values lists, and then the dict() constructor is called to create a dictionary from the pairs.

Note that both methods assume that the lists have the same length and that the order of the elements in both lists are correlated (i.e., the first element in the keys list corresponds to the first element in the values list, and so on). If you have duplicate keys or values, the second occurrence will overwrite the first one in the resulting dictionary. Also, if the lists have different lengths, you will get a ValueError from the zip() function.