Sub topic 8
Merging lists and dictionaries with unpacking
This chapter assumes you know how * and ** unpack values into function calls, and that you are comfortable with lists, tuples, sets and dictionaries. Here you will use the same two operators inside literals to build new collections from existing ones.
Unpacking inside a literal
At a call site, * spreads a sequence into separate arguments. The same operator works inside list, tuple and set literals. Python takes each item from the iterable and places it where the starred expression appears.
first = [1, 2]
combined = [*first, 3, *range(4, 6)]
print(combined) # [1, 2, 3, 4, 5]You can mix starred items and ordinary items in any order. The result is a new list, and first is not changed.
Any iterable works after the *, not only lists. A string unpacks into its characters, and a range unpacks into its numbers.
letters = [*"abc"]
print(letters) # ['a', 'b', 'c']
evens = (0, 2)
odds = (1, 3)
print((*evens, *odds)) # (0, 2, 1, 3)
print({*evens, *odds}) # {0, 1, 2, 3} (set order may vary)The second line builds a tuple, and the third builds a set. In a set, duplicate values collapse into one.
Merging dictionaries with `**`
Inside a dictionary literal, ** copies every key and value from another mapping.
defaults = {"color": "red", "size": 1}
overrides = {"size": 3}
merged = {**defaults, **overrides}
print(merged) # {'color': 'red', 'size': 3}Python processes the items from left to right. When a key repeats, the later value replaces the earlier one. That is why size is 3 in the result. Put the defaults first and the overrides last.
You can also mix ** with ordinary key: value pairs.
settings = {"color": "red", "size": 1}
custom = {**settings, "size": 10, "bold": True}
print(custom) # {'color': 'red', 'size': 10, 'bold': True}A replaced key keeps the position it had when it was first inserted. Only its value changes.
a = {"x": 1, "y": 2}
b = {"x": 9}
print({**a, **b}) # {'x': 9, 'y': 2}Literal unpacking and call unpacking differ on duplicates
A dictionary literal accepts repeated keys and lets the last one win. A function call does not. If two ** expressions supply the same keyword, Python raises a TypeError.
def show(**kwargs):
return kwargs
a = {"size": 1}
b = {"size": 3}
print({**a, **b}) # {'size': 3}
try:
show(**a, **b)
except TypeError as error:
print(error) # show() got multiple values for keyword argument 'size'Use this difference when you choose a tool. If you want "later wins", build a dictionary first and pass it with a single **.
print(show(**{**a, **b})) # {'size': 3}Other ways to merge
Unpacking is not the only option. The table compares the common ones.
| Approach | Works with | Result | Column |
|---|---|---|---|
| `[*a, *b]` | Any iterables | New list | |
| `a + b` | Two lists only | New list | |
| `{**a, **b}` | Any mappings | New dictionary | |
| `a \ | b` | Two dictionaries (Python 3.9+) | New dictionary |
| `a.update(b)` | Two dictionaries | Changes `a` in place |
The + operator needs both sides to be lists. Unpacking lets you combine a list, a tuple and a range in one expression, and it lets you insert single items between them. For dictionaries, {**a, **b} and a | b give the same result when both are plain dictionaries.
The copies are shallow
Unpacking copies references, not the objects behind them. If a value is a list or a dictionary, the new collection and the original share it.
base = {"tags": ["a", "b"]}
copy = {**base}
copy["tags"].append("c")
print(base["tags"]) # ['a', 'b', 'c']Reassigning a key in copy does not affect base. Changing a shared mutable value does. If you need independent nested data, use copy.deepcopy() from the standard library.
A practical pattern: configuration layers
A common use is layering settings from least to most specific.
def build_config(user=None, **cli_options):
base = {"debug": False, "port": 8000}
user = user or {}
return {**base, **user, **cli_options}
print(build_config({"port": 9000}, debug=True))
# {'debug': True, 'port': 9000}The function collects extra keywords with **cli_options. It then merges three layers in order of increasing priority. Command-line options override the user file, and the user file overrides the built-in defaults.
Key points
[*a, *b],(*a, *b)and{*a, *b}build a list, tuple or set from any iterables.{**a, **b}builds a dictionary, and the rightmost value wins for repeated keys.- Dictionary literals allow repeated keys. Function calls with repeated
**keys raise aTypeError. - Every merge makes a shallow copy.
Exercise
What does this code print, and why? x = {"a": 1, "b": 2}, y = {"b": 3, "c": 4}, print({**y, **x, "c": 0})
Show answer
It prints {'b': 2, 'c': 0, 'a': 1}. Python processes the items left to right. First y supplies b=3 and c=4. Then x replaces b with 2 and adds a=1. Finally the literal pair "c": 0 replaces c. The keys keep the order in which they were first inserted (b, c, a), so the output order is b, c, a.
Exercise
Write a function join_all(*groups) that takes any number of lists and returns one list containing every item, with the string "END" added after the last item. Use unpacking inside a list literal.
Show answer
def joinall(groups): return [(item for group in groups for item in group), "END"] A simpler version that gives the same result: def joinall(groups): result = [] for group in groups: result.extend(group) return [result, "END"] For example, join_all([1, 2], [3]) returns [1, 2, 3, "END"].