PythonMastery
Python programs · Lists · beginner

Convert two lists into a dictionary in Python

Turn a list of keys and a list of values into one dictionary with dict(zip(keys, values)), and catch lists of different lengths with strict=True.

zip() pairs up the items of two lists, and dict() turns those pairs into a dictionary.

The program

python
countries = ["France", "Japan", "Kenya"]
capitals = ["Paris", "Tokyo", "Nairobi"]

capital_of = dict(zip(countries, capitals))

print(capital_of)
print("The capital of Japan is", capital_of["Japan"])
output
{'France': 'Paris', 'Japan': 'Tokyo', 'Kenya': 'Nairobi'}
The capital of Japan is Tokyo

How it works

Lists of different lengths

zip() stops at the end of the shorter list, so extra items are dropped without any error. Add strict=True (Python 3.10 and later) to get an error instead:

python
keys = ["name", "language", "year"]
values = ["Ada", "Python"]

print(dict(zip(keys, values)))

try:
    dict(zip(keys, values, strict=True))
except ValueError as error:
    print("Error:", error)
output
{'name': 'Ada', 'language': 'Python'}
Error: zip() argument 2 is shorter than argument 1

The key "year" was lost in the first line. When the two lists should always have the same length, strict=True shows the mistake at once.

Related programs: enumerate and zip together.

Learn the idea: Lists & Sequences, Dictionaries, Loops: for, while, and the Pythonic Patterns