Build a Python dictionary from two lists
Combine keys and values with dict and zip, reject mismatched lengths, handle duplicate keys, and avoid unexpected keys when filling missing values.
Use dict(zip(keys, values)) to pair two lists by position and build a dictionary. If mismatched lengths would indicate bad data, use strict=True on Python 3.10 or later.
keys = ["a", "b", "c"]
values = [1, 2, 3]
result = dict(zip(keys, values, strict=True))
print(result) # {'a': 1, 'b': 2, 'c': 3}
Decide how to handle unequal lengths
Ordinary zip() stops when the shorter input ends:
keys = ["a", "b", "c", "d"]
values = [1, 2, 3]
print(dict(zip(keys, values))) # {'a': 1, 'b': 2, 'c': 3}
Here, "d" is omitted. With strict=True, consuming the mismatched pairs raises ValueError rather than silently truncating them. For older Python versions and actual lists, compare their lengths before constructing the dictionary.
Other ways to pair the inputs
An indexed comprehension works when corresponding values exist:
keys = ["a", "b"]
values = [1, 2]
result = {key: values[index] for index, key in enumerate(keys)}
Unlike zip(), this raises IndexError if values is too short, but silently ignores extra values. Strict zip() expresses an equal-length requirement more directly.
To fill missing values, zip_longest() can help, provided keys are not missing:
from itertools import zip_longest
keys = ["a", "b", "c"]
values = [1, 2]
if len(values) > len(keys):
raise ValueError("Each value needs a key")
result = dict(zip_longest(keys, values, fillvalue=None))
print(result) # {'a': 1, 'b': 2, 'c': None}
Without the length guard, extra values would be paired with a None key, and repeated missing keys could overwrite each other.
FAQ
Why wrap zip() in dict()? zip() yields an iterator of pairs. dict() consumes those pairs to create the mapping.
What happens with duplicate keys? Later values replace earlier ones. Keys must also be hashable; a list cannot serve as a dictionary key.
How do I get the two lists back? Use list(result.keys()) and list(result.values()) without changing the dictionary between the calls. Dictionaries preserve insertion order in Python 3.7 and later, so those lists line up by position.
References
Contact us
Join the community
to join the community
Try Guance
Start online and pay only for what you use.
Get startedChoose a Guance plan