Sub topic 9
Building dicts and unzipping with zip
This chapter assumes you can already loop over two sequences with zip, use tuple unpacking in a for header, and know that zip stops at the shortest input. You also need to be comfortable reading dictionaries and tuples, and to know that zip returns a one-shot iterator. Earlier chapters covered all of that. Here zip is used as a data-shaping tool instead of a loop helper.
Two idioms do most of the work:
dict(zip(keys, values))turns two parallel sequences into a dictionary.zip(*pairs)splits a sequence of tuples back into separate sequences. This is called unzipping.
Both rely on facts about zip you already know, plus two details: how dict() consumes pairs, and what the * operator does in a function call.
Building a dictionary from two parallel lists
Data often arrives as parallel lists, where position i in one list belongs with position i in another. Header names and row values from a CSV file are a typical case. A dictionary is usually easier to work with.
keys = ["name", "language", "level"]
values = ["Ada", "Python", "advanced"]
profile = dict(zip(keys, values))
print(profile)
# {'name': 'Ada', 'language': 'Python', 'level': 'advanced'}This works because the dict() constructor accepts an iterable of key/value pairs, and zip produces exactly that: one 2-tuple per position. No intermediate list is built. dict() pulls pairs from zip one at a time and stores each one.
The loop equivalent shows what happens inside:
keys = ["name", "language", "level"]
values = ["Ada", "Python", "advanced"]
profile = {}
for key, value in zip(keys, values):
profile[key] = value
print(profile)Use dict(zip(...)) when you want the pairs as they are. Use the loop or a comprehension when you need to change them on the way in.
Duplicate keys: the last one wins
A dictionary holds each key once. If the key list contains duplicates, later values overwrite earlier ones, and no error is raised:
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's order, because it was first inserted there. Only its value changes. If duplicates are a sign of bad data, check for them before building the dictionary:
keys = ["a", "b", "a"]
if len(set(keys)) != len(keys):
print("duplicate keys found")Unequal lengths silently lose data
The default truncation rule applies here too. When the value list is shorter, the extra keys vanish without a warning:
keys = ["a", "b", "c"]
values = [1, 2]
print(dict(zip(keys, values)))
# {'a': 1, 'b': 2}For this idiom a length mismatch is almost always a bug, so strict=True (Python 3.10+) is a good default:
keys = ["a", "b", "c"]
values = [1, 2]
try:
result = dict(zip(keys, values, strict=True))
except ValueError:
print("keys and values differ in length")If you want every key present, with a placeholder for the missing values, use zip_longest:
from itertools import zip_longest
keys = ["a", "b", "c"]
values = [1, 2]
print(dict(zip_longest(keys, values)))
# {'a': 1, 'b': 2, 'c': None}Be careful with the opposite case. If there are more values than keys, zip_longest produces pairs whose key is the fill value. All of those collapse into a single None key. Padding is only safe when the keys are the longer input.
Keys must be hashable
Dictionary keys must be hashable. Strings, numbers, and tuples of those are fine. Lists and dictionaries are not:
try:
dict(zip([[1], [2]], ["x", "y"]))
except TypeError as error:
print(error)
# unhashable type: 'list'If your keys are lists, convert each one to a tuple first.
Choosing between dict(zip()) and a comprehension
A dictionary comprehension over zip does the same job and lets you transform keys or values as you go:
items = ["apple", "pear", "fig"]
raw_prices = ["1.20", "0.80", "2.50"]
prices = {item: float(price) for item, price in zip(items, raw_prices)}
print(prices)
# {'apple': 1.2, 'pear': 0.8, 'fig': 2.5}The two forms compare like this:
| Situation | Better choice |
|---|---|
| Pairs go straight into the dictionary | `dict(zip(keys, values))` |
| You convert or clean keys or values | `{k: f(v) for k, v in zip(...)}` |
| You skip some pairs | Comprehension with an `if` clause |
| You add pairs to an existing dictionary | `existing.update(zip(keys, values))` |
update accepts the same iterable of pairs as dict(), so it fits naturally:
config = {"debug": False}
config.update(zip(["host", "port"], ["localhost", 8080]))
print(config)
# {'debug': False, 'host': 'localhost', 'port': 8080}Inverting a dictionary
Swapping keys and values is another use of zip. A dictionary's .values() and .keys() views iterate in the same order, so zipping them in reverse order gives inverted pairs:
ages = {"Ada": 36, "Grace": 45}
by_age = dict(zip(ages.values(), ages.keys()))
print(by_age)
# {36: 'Ada', 45: 'Grace'}This only works cleanly when the values are unique and hashable. If two keys share a value, the last one overwrites the other and data disappears:
scores = {"Ada": 90, "Grace": 85, "Linus": 90}
print(dict(zip(scores.values(), scores.keys())))
# {90: 'Linus', 85: 'Grace'}Ada's entry is gone. When values may repeat, group the keys into lists instead of inverting with zip.
Unzipping with zip(*pairs)
Zipping combines several sequences into one sequence of tuples. Unzipping does the reverse. The same function does both, thanks to the * operator in a call.
In a function call, *sequence spreads the sequence's items out as separate positional arguments. These two calls are identical:
pairs = [(1, "x"), (2, "y"), (3, "z")]
a = list(zip(*pairs))
b = list(zip((1, "x"), (2, "y"), (3, "z")))
print(a == b)
# TrueNow zip receives three tuples. It takes the first item of each (1, 2, 3), then the second item of each ("x", "y", "z"). The result has two tuples, one per column:
pairs = [(1, "x"), (2, "y"), (3, "z")]
numbers, letters = zip(*pairs)
print(numbers)
# (1, 2, 3)
print(letters)
# ('x', 'y', 'z')The unpacking on the left side works because zip is an iterator that yields exactly two tuples here. The number of names on the left must match the length of each pair. Pairs of length 3 would need three names, and two names would raise ValueError: too many values to unpack.
The pieces come back as tuples, not lists. If you need lists, convert them:
pairs = [(1, "x"), (2, "y"), (3, "z")]
numbers, letters = map(list, zip(*pairs))
print(numbers)
# [1, 2, 3]
print(letters)
# ['x', 'y', 'z']A diagram of the round trip
The diagram follows data from two lists to a dictionary and back to two sequences.
Splitting a dictionary into keys and values
d.items() yields (key, value) pairs, so unzipping it separates keys from values. Combined with sorted, this gives you both sides of a ranked table:
scores = {"Ada": 95, "Grace": 88, "Linus": 91}
ranked = sorted(scores.items(), key=lambda item: item[1], reverse=True)
names, values = zip(*ranked)
print(names)
# ('Ada', 'Linus', 'Grace')
print(values)
# (95, 91, 88)This pattern is common when you need two aligned sequences for a chart, a table, or a function that takes separate arguments.
The round trip
If you build a dictionary and then unzip its items, you get the original sequences back, provided the keys were unique:
names = ["Ada", "Grace", "Linus"]
scores = [95, 88, 91]
table = dict(zip(names, scores))
names_back, scores_back = zip(*table.items())
print(list(names_back) == names)
# True
print(list(scores_back) == scores)
# TrueIf the keys contained duplicates, the round trip would be shorter than the original, because the dictionary merged them.
Unzipping an empty sequence
There is one edge case worth guarding. If pairs is empty, zip(*pairs) is zip() with no arguments, and it yields nothing. Unpacking that into two names fails:
pairs = []
try:
numbers, letters = zip(*pairs)
except ValueError as error:
print(error)
# not enough values to unpack (expected 2, got 0)This often appears in real code, for example when a filter removes every row. Handle it explicitly:
pairs = []
numbers, letters = zip(*pairs) if pairs else ((), ())
print(numbers, letters)
# () ()Transposing a matrix
A matrix stored as a list of rows is a list of lists. Unzipping turns rows into columns, which is the same operation as a transpose:
matrix = [
[1, 2, 3],
[4, 5, 6],
]
columns = list(zip(*matrix))
print(columns)
# [(1, 4), (2, 5), (3, 6)]
as_lists = [list(column) for column in zip(*matrix)]
print(as_lists)
# [[1, 4], [2, 5], [3, 6]]Once you have columns, per-column statistics are short:
matrix = [
[1, 2, 3],
[4, 5, 6],
]
print([sum(column) for column in zip(*matrix)])
# [5, 7, 9]Ragged rows
If the rows have different lengths, zip(*rows) truncates to the shortest row and drops data without warning. zip_longest keeps everything and pads the gaps:
from itertools import zip_longest
rows = [[1, 2, 3], [4, 5]]
print(list(zip(*rows)))
# [(1, 4), (2, 5)]
print(list(zip_longest(*rows, fillvalue=0)))
# [(1, 4), (2, 5), (3, 0)]You can also pass strict=True to zip(*rows) when ragged input should be an error rather than something to repair.
Pitfalls
Most problems with these idioms come from a few causes:
| Symptom | Cause | Fix |
|---|---|---|
| Dictionary is missing keys | Values list was shorter, so `zip` truncated | Use `strict=True`, or `zip_longest` for padding |
| Fewer entries than expected | Duplicate keys overwrote each other | Check `len(set(keys)) == len(keys)` first |
| `TypeError: unhashable type` | A key is a list or dictionary | Convert keys to tuples |
| `ValueError` when unpacking `zip(*pairs)` | Name count does not match pair length, or `pairs` is empty | Match the number of names, and guard against empty input |
| Unzipped results are tuples | `zip` always yields tuples | Wrap with `list` or `map(list, ...)` |
| Second use of a `zip` object is empty | It is a one-shot iterator | Build the dictionary or list once and reuse it |
The last row matters here. dict(zip(keys, values)) consumes the zip object completely, and so does unpacking with a, b = zip(*pairs). Store the result, not the zip object. Also note that zip(*pairs) expands pairs into an argument list first. If pairs is a generator, the star pulls every item into memory at once, so this idiom does not stream very large inputs.
Summary of the idioms
dict(zip(keys, values))builds a dictionary from parallel sequences. Later duplicate keys overwrite earlier ones, and unequal lengths truncate unless you say otherwise.d.update(zip(keys, values))adds pairs to an existing dictionary.dict(zip(d.values(), d.keys()))inverts a dictionary, but loses entries when values repeat.a, b = zip(*pairs)unzips pairs into tuples. The name count must match the pair length, and empty input needs a guard.zip(*matrix)transposes rows into columns, andzip_longest(*rows, fillvalue=...)handles ragged rows.
Exercise
What does this code print, and why? keys = ["x", "y", "x", "z"] values = [1, 2, 3, 4] print(dict(zip(keys, values)))
Show answer
It prints {'x': 3, 'y': 2, 'z': 4}. The key "x" appears twice, so the pair ("x", 3) overwrites ("x", 1). The key keeps its original position in the dictionary, which is why "x" is still listed first.
Exercise
You have rows = [("Ada", 95), ("Grace", 88), ("Linus", 91)]. Write code that produces the list of names and the list of scores as two separate lists (not tuples), and explain what happens if rows is empty.
Show answer
names, scores = map(list, zip(rows)) gives names == ["Ada", "Grace", "Linus"] and scores == [95, 88, 91]. If rows is empty, zip(rows) yields nothing, so unpacking into two names raises ValueError (not enough values to unpack, expected 2, got 0). Guard it with: names, scores = map(list, zip(*rows)) if rows else ([], []).
Exercise
Given matrix = [[1, 2, 3], [4, 5]], what does list(zip(*matrix)) return, and how would you keep the missing entry as 0 instead of dropping the third column?
Show answer
It returns [(1, 4), (2, 5)], because zip truncates to the shortest row and the 3 is lost. To keep it, use itertools.ziplongest with a fill value: list(ziplongest(*matrix, fillvalue=0)) returns [(1, 4), (2, 5), (3, 0)].