Sub topic 9
Building dicts and unzipping with zip
This chapter covers two uses of zip that reshape data instead of just looping over it: building a dictionary from two parallel lists, and splitting a list of pairs back into separate sequences. It assumes you know how zip pairs items, how tuple unpacking works in a for loop, and the basics of lists, tuples, and dictionaries.
Building a dictionary from two lists
A dictionary needs key-value pairs. If your keys and values live in two separate lists at matching positions, zip produces exactly the pairs the dict constructor wants.
The dict constructor accepts any iterable of two-item pairs. zip(keys, values) yields tuples such as ("a", 1), so you can pass it straight in.
keys = ["a", "b", "c"]
values = [1, 2, 3]
lookup = dict(zip(keys, values))
print(lookup)
# {'a': 1, 'b': 2, 'c': 3}No intermediate list is needed. dict consumes the zip iterator one pair at a time.
A practical example
Parallel lists often come from files or spreadsheets: one row of headers and one row of data. Zipping them gives a record you can look up by name.
headers = ["name", "role", "level"]
row = ["Ada", "engineer", 3]
record = dict(zip(headers, row))
print(record["role"])
# engineerWatch the lengths and the keys
Two rules from earlier chapters still apply here.
zipstops at the shortest input. Ifvaluesis shorter thankeys, the extra keys are silently dropped. Usezip(keys, values, strict=True)(Python 3.10+) when a mismatch should be an error.- Dictionary keys are unique. If
keyscontains a repeated item, later values overwrite earlier ones.
keys = ["a", "b", "a"]
values = [1, 2, 3]
print(dict(zip(keys, values)))
# {'a': 3, 'b': 2}The key "a" keeps its original position in the dictionary but takes the last value, 3. Nothing warns you about the lost 1.
Unzipping with zip(*pairs)
zip can also run in reverse. Suppose you have a list of pairs and want one sequence of first items and one of second items.
pairs = [(1, "x"), (2, "y"), (3, "z")]
numbers, letters = zip(*pairs)
print(numbers)
# (1, 2, 3)
print(letters)
# ('x', 'y', 'z')The * in a call is the argument-unpacking operator. It spreads the list into separate arguments, so zip(*pairs) is the same as writing:
zip((1, "x"), (2, "y"), (3, "z"))zip now sees three inputs and groups by position. The first items of all three tuples go together, then the second items. That regrouping turns rows into columns.
The two names on the left (numbers, letters) unpack the two resulting tuples. The results are tuples, not lists. Wrap them in list() if you need to modify them.
numbers, letters = map(list, zip(*pairs))
print(numbers)
# [1, 2, 3]Transposing a table
Unzipping is a general transpose. Any list of equal-length rows becomes a list of columns.
rows = [
(1, 2, 3),
(4, 5, 6),
]
columns = list(zip(*rows))
print(columns)
# [(1, 4), (2, 5), (3, 6)]Here each inner tuple holds the values from one column of the original table.
Common errors
Unzipping an empty list fails when you try to unpack the result. zip(*[]) calls zip() with no arguments, which yields nothing, so the line below raises ValueError: not enough values to unpack.
pairs = []
try:
numbers, letters = zip(*pairs)
except ValueError as error:
print(error)
# not enough values to unpack (expected 2, got 0)Guard against empty input if your data may be empty.
pairs = []
numbers, letters = zip(*pairs) if pairs else ((), ())
print(numbers, letters)
# () ()Rows of different lengths are another source of surprises. zip(*rows) truncates to the shortest row, so data can vanish without an error.
rows = [(1, 2, 3), (4, 5)]
print(list(zip(*rows)))
# [(1, 4), (2, 5)]The 3 is gone. Pass strict=True if the rows must match.
Choosing between approaches
| Goal | Tool |
|---|---|
| Two lists into a dictionary | `dict(zip(keys, values))` |
| Rows into columns, or columns into rows | `zip(*rows)` |
| A list of pairs into two sequences | `a, b = zip(*pairs)` |
| Keys and values with mismatched lengths | `zip(..., strict=True)` or `itertools.zip_longest` |
If you already have a dictionary and want a list of pairs, dict.items() gives you the pairs directly, and zip(*d.items()) splits them into a tuple of keys and a tuple of values.
lookup = {"a": 1, "b": 2, "c": 3}
keys, values = zip(*lookup.items())
print(keys)
# ('a', 'b', 'c')
print(values)
# (1, 2, 3)Exercise
You have names = ["Ada", "Grace", "Linus"] and scores = [95, 88, 91]. Write code that builds a dictionary mapping each name to its score, then uses zip to split the dictionary's items back into a tuple of names and a tuple of scores. What happens to the result if names contains "Ada" twice?
Show answer
Build it with lookup = dict(zip(names, scores)). Then split it with namesout, scoresout = zip(*lookup.items()). If "Ada" appears twice, the dictionary keeps only one "Ada" entry, holding the score from the later position, so the unzipped tuples are shorter than the original lists and one score is lost without any error.