How to Create a Dict from Two Parallel Lists in Python (zip)
Build a dictionary by pairing elements from two parallel lists using Python's built-in zip function and dict constructor.
Python code
5 lineskeys = ["name", "age", "city"]
values = ["Alice", 30, "New York"]
result = dict(zip(keys, values))
print(result)
Output
{'name': 'Alice', 'age': 30, 'city': 'New York'}
How it works
The zip function pairs the first element of keys with the first element of values, the second with the second, and so on, producing an iterator of tuples. The dict() constructor consumes these tuples and converts each tuple (key, value) into a dictionary entry. This works because each tuple has exactly two elements — the key and the value. If the lists are of unequal length, zip stops at the shorter one, which silently drops extra elements — be aware of that behavior. For most everyday use, this one-liner is the cleanest way to merge two aligned lists into a mapping.
Common mistakes
- Forgetting that zip stops at the shorter list, silently discarding extra elements
- Assuming order is preserved (it is, but rely on insertion order carefully when keys are not unique)
- Using two separate loops when zip can do it in one line
Variations
- Use a dictionary comprehension: {k: v for k, v in zip(keys, values)}
- Convert zip output to a list then to dict: dict(list(zip(keys, values)))
Real-world use cases
- Mapping CSV column headers (as keys) to a row of cell values in data processing.
- Combining an API response's field names with their corresponding values to form a JSON-ready dict.
- Pairing configuration keys with user-provided settings loaded from parallel input arrays.
Sponsored
More from Dictionaries & sets
- Build a Case-Insensitive Dict with a Wrapper Class in Python medium
- Build a defaultdict histogram of categories in Python easy
- Build adjacency dict graph from edges in Python easy
- Build an OrderedDict insertion order demo in Python 3 easy
- Check Invertible Mapping for Duplicate Values in Python easy
- Compare Two Dictionaries in Python easy
Keep learning
Related tutorials and quizzes for this topic.