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 TokyoHow it works
zip(countries, capitals)gives the pairs("France", "Paris"),("Japan", "Tokyo")and("Kenya", "Nairobi").dict()uses the first item of each pair as the key and the second as the value.- If a key appears twice in the first list, the dictionary keeps the last value for it.
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 1The 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.