How to create a dictionary from two lists in python

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

To create a dictionary from two lists in Python, you can use the built-in zip() function with the dict() constructor. Here’s an example:

keys = ['a', 'b', 'c']
values = [1, 2, 3]
my_dict = dict(zip(keys, values))
print(my_dict)

In this example, the zip() function is used to pair up the elements of the keys and values lists, and then the dict() constructor is used to convert the resulting list of pairs into a dictionary. The output will be 'a': 1, 'b': 2, 'c': 3 .

If the two lists have different lengths, the resulting dictionary will have the length of the shorter list. You can also convert the lists into tuples or sets before using zip() to create a dictionary.

Note that if the lists have duplicate values, the resulting dictionary will have the last value in the list for each key. If you want to preserve all the values, you can use a dictionary comprehension with the zip() function:

keys = ['a', 'b', 'c', 'a']
values = [1, 2, 3, 4]
my_dict = { k:v for k,v in zip(keys, values) }
print(my_dict)

In this example, the duplicate key 'a' is present in the keys list, so the resulting dictionary will have the value 4 for that key. The output will be 'a': 4, 'b': 2, 'c': 3 .

Tags: