Sub topic 8
Merging lists and dictionaries with unpacking
This chapter assumes you know how *args and **kwargs collect arguments in a function signature, and how * and ** spread values at a call site. It also assumes you know how to read tuples, lists and dictionaries. The new idea here is that the same two operators also work inside list, tuple, set and dictionary literals. The feature comes from PEP 448 and has been available since Python 3.5.
The idea: one operator, a new place
In a call, *items feeds each element of items to the function as a separate positional argument. In a literal, *items places each element of items into the new container at that spot. The dictionary forms work the same way: **mapping places each key and value pair into the new dictionary.
You do not call a function or mutate anything. You write the shape of the result and list the pieces that fill it.
Unpacking into lists, tuples and sets
Any iterable can follow a * inside a literal. This includes lists, tuples, strings, ranges, generators, sets and dictionaries.
first = [1, 2]
second = (3, 4)
combined = [*first, *second, 5, *range(6, 8), *"ab"]
print(combined) # [1, 2, 3, 4, 5, 6, 7, 'a', 'b']Plain values and unpacked iterables can be mixed in any order, and the result is built left to right. The container type comes from the brackets you write, not from the sources.
a = [1, 2, 2]
b = [2, 3]
print([*a, *b]) # [1, 2, 2, 2, 3]
print((*a, *b)) # (1, 2, 2, 2, 3)
print(sorted({*a, *b})) # [1, 2, 3]The set version removes duplicates because that is what a set does. The list and tuple versions keep every element.
A tuple literal with a single starred item needs a trailing comma, because the comma is what makes a tuple.
numbers = [1, 2, 3]
as_tuple = (*numbers,)
print(as_tuple) # (1, 2, 3)* also works in other places that accept an expression list, such as return statements and for loops.
def split_and_tag(items):
return *items, "done"
print(split_and_tag([1, 2])) # (1, 2, 'done')
for value in *first, *second:
print(value, end=" ") # 1 2 3 4
print()Unpacking is not the same as starred assignment
You may also have seen * on the left side of an assignment.
head, *tail = [1, 2, 3, 4]
print(head) # 1
print(tail) # [2, 3, 4]This is related to *args. It collects the leftover items into a new list, in the same way *args collects extra arguments into a tuple. Unpacking in a literal goes the other direction. It spreads items out into a container.
Iterables are consumed once
If the source is an iterator or generator, unpacking uses it up.
squares = (n * n for n in range(4))
print([*squares]) # [0, 1, 4, 9]
print([*squares]) # []The second line prints an empty list because the generator is exhausted. Convert a generator to a list first if you need to reuse it.
What a dictionary gives you under `*`
Starring a dictionary iterates over it, and iterating a dictionary yields keys. Use .items(), .values() or .keys() to choose what you spread.
prices = {"apple": 3, "pear": 5}
print([*prices]) # ['apple', 'pear']
print([*prices.values()]) # [3, 5]
print([*prices.items()]) # [('apple', 3), ('pear', 5)]Merging dictionaries with `**`
Inside a dictionary literal, **mapping inserts every key and value pair from mapping. Several of them can appear in one literal, along with ordinary key: value entries.
defaults = {"color": "red", "size": 1, "visible": True}
overrides = {"size": 3, "color": "blue"}
merged = {**defaults, **overrides}
print(merged) # {'color': 'blue', 'size': 3, 'visible': True}The rule that decides conflicts is that later entries win. Python inserts the entries from left to right. When a key appears again, its value is replaced.
Key order after a conflict
A replaced key keeps its original position. Only the value changes. That means the order of the sources affects the output order as well as the values.
x = {"a": 1, "b": 2}
y = {"b": 20, "c": 3}
print({**x, **y}) # {'a': 1, 'b': 20, 'c': 3}
print({**y, **x}) # {'b': 2, 'c': 3, 'a': 1}In the second line, b is inserted first with the value 20. The later x then replaces that value with 2, but b stays at the front.
Mixing unpacked and explicit entries
The position of an explicit entry decides whether it overrides or is overridden.
user = {"name": "Ada", "role": "viewer"}
admin = {**user, "role": "admin"}
forced = {"role": "admin", **user}
print(admin) # {'name': 'Ada', 'role': 'admin'}
print(forced) # {'role': 'viewer', 'name': 'Ada'}Put the explicit entry after the unpacking when you want it to win. Put it before when you are supplying a fallback.
Choosing between merge techniques
Python has several ways to combine collections. They differ in whether they create a new object, which versions support them, and what they accept.
| Technique | Creates new object | Python version | Notes | Column |
|---|---|---|---|---|
| `{**a, **b}` | Yes | 3.5+ | Accepts any mappings, and you can add explicit entries inline | |
| `a \ | b` | Yes | 3.9+ | Both operands must be dictionaries or compatible types |
| `a.update(b)` | No, it changes `a` | All | Returns `None` | |
| `dict(a, **b)` | Yes | All | Keys of `b` must be strings | |
| `[*a, *b]` | Yes | 3.5+ | Accepts any iterables | |
| `a + b` | Yes | All | Lists only, and both sides must be lists | |
| `a.extend(b)` | No, it changes `a` | All | Returns `None` |
Unpacking is the most flexible option because the sources can be of different types. [*my_list, *my_tuple] works, while my_list + my_tuple raises a TypeError. The result is always a plain list, tuple, set or dict, even if a source was a subclass such as OrderedDict.
Prefer update() or extend() when you intend to modify an existing object. Prefer unpacking when you want a new object and the original must stay untouched.
Shallow copies and nested data
Every merge above copies one level only. The new container holds references to the same inner objects as the sources.
config = {"db": {"host": "localhost"}, "debug": False}
copy = {**config}
copy["db"]["host"] = "example.com"
copy["debug"] = True
print(config) # {'db': {'host': 'example.com'}, 'debug': False}Changing copy["debug"] left config alone, because that entry was replaced in the copy. Changing copy["db"]["host"] altered config as well, because both dictionaries point to the same inner dictionary.
The same applies to nested merges. If both sources have a "db" key, the later whole dictionary replaces the earlier one. Their contents are not combined.
base = {"db": {"host": "localhost", "port": 5432}}
override = {"db": {"host": "example.com"}}
print({**base, **override}) # {'db': {'host': 'example.com'}}The port entry is gone. When you need a recursive merge, write one explicitly.
def deep_merge(base, override):
result = {**base}
for key, value in override.items():
if isinstance(value, dict) and isinstance(result.get(key), dict):
result[key] = deep_merge(result[key], value)
else:
result[key] = value
return result
base = {"db": {"host": "localhost", "port": 5432}, "debug": False}
override = {"db": {"host": "example.com"}}
print(deep_merge(base, override))
# {'db': {'host': 'example.com', 'port': 5432}, 'debug': False}The function still starts with {**base} to avoid changing the input at the top level. It does not copy inner values that override leaves alone, so those are still shared with base.
Practical patterns
Defaults plus caller options
The most common use is to combine built-in defaults with options supplied by the caller. Placing the caller's values last lets them win.
def build(options=None):
return {"retries": 3, "timeout": 10, **(options or {})}
print(build())
# {'retries': 3, 'timeout': 10}
print(build({"retries": 5, "verbose": True}))
# {'retries': 5, 'timeout': 10, 'verbose': True}The expression options or {} handles the case where options is None. Unpacking None with ** raises TypeError: 'NoneType' object is not a mapping. The same applies to *None in a list literal.
Including an entry only when a condition holds
A conditional expression that produces either a small container or an empty one makes an optional entry.
def make_headers(token=None):
return {
"Accept": "application/json",
**({"Authorization": f"Bearer {token}"} if token else {}),
}
print(make_headers())
# {'Accept': 'application/json'}
print(make_headers("abc123"))
# {'Accept': 'application/json', 'Authorization': 'Bearer abc123'}The list version works the same way.
def pick_files(required, extra=None):
return [*required, *([extra] if extra is not None else [])]
print(pick_files(["a.txt"])) # ['a.txt']
print(pick_files(["a.txt"], "b.txt")) # ['a.txt', 'b.txt']Do not overuse this form. If you need more than one condition, build the container in steps with ordinary if statements.
Adding a prefix, suffix or separator
parts = ["alpha", "beta"]
command = ["run", *parts, "--verbose"]
print(command) # ['run', 'alpha', 'beta', '--verbose']Differences from unpacking in calls
The same ** symbol is more permissive in a literal than in a call. Two differences cause confusing errors.
Duplicate keys
In a dictionary literal, a repeated key is fine and the later value wins. In a call, a repeated keyword is an error.
def show(**kwargs):
return kwargs
a = {"x": 1}
b = {"x": 2}
print({**a, **b}) # {'x': 2}
try:
show(**a, **b)
except TypeError as error:
print(type(error).__name__) # TypeErrorWhen you want call-site merging with override semantics, merge first and pass the result: show(**{**a, **b}).
Key types
A dictionary literal accepts any hashable key. A call requires every key to be a string, since the keys become parameter names.
numbers = {1: "one", 2: "two"}
print({**numbers, 3: "three"}) # {1: 'one', 2: 'two', 3: 'three'}
try:
show(**numbers)
except TypeError as error:
print(type(error).__name__) # TypeErrorCommon errors
| Mistake | What happens | Fix |
|---|---|---|
| `{**None}` or `[*None]` | `TypeError` because `None` is not a mapping or an iterable | Use `options or {}` or `items or []` |
| `[*some_dict]` when you wanted pairs | You get only the keys | Use `[*some_dict.items()]` |
| `{*some_dict.items()}` when you wanted a dictionary | You get a set of tuples | Use `{**some_dict}` |
| `{**a, **b}` with a shared nested dictionary | The inner dictionary from `b` replaces the one from `a` | Use a recursive merge such as `deep_merge` |
| Mutating a merged result's nested values | The original sources change too | Copy nested values with `copy.deepcopy()` when you need isolation |
| Reusing a generator after unpacking it | The second use sees nothing | Convert it to a list first |
The set versus dictionary mix-up deserves attention. A single star builds a set and a double star builds a dictionary, but {*x} and {**x} look almost identical. If a dictionary you merged shows up as a set of keys, check the star count.
Exercises
Exercise
What does this code print? base = {"a": 1, "b": 2} extra = {"b": 3, "c": 4} print({extra, base, "d": 5})
Show answer
{'b': 2, 'c': 4, 'a': 1, 'd': 5}. The key b is first inserted from extra with the value 3. Then base replaces its value with 2 but b keeps its first position. After that come c from extra (already inserted), a from base and the explicit d.
Exercise
Write a function named combine that takes a list named first and a tuple named second and returns one new list containing all of first, then all of second, followed by the string "end". Then explain why first + second would not work here.
Show answer
def combine(first, second): return [first, second, "end"] The expression first + second raises a TypeError because the + operator on lists requires both operands to be lists, and second is a tuple. Unpacking accepts any iterable.
Exercise
A function receives options, which may be None or a dictionary. It must return a dictionary that starts with {"mode": "fast"} and lets options override it. Write the function, and say what happens if you write {"mode": "fast", **options} without handling None.
Show answer
def settings(options=None): return {"mode": "fast", (options or {})} Without the "or {}" guard, calling settings() raises TypeError: 'NoneType' object is not a mapping, because cannot unpack None.
Exercise
Given a = {"x": 1} and b = {"x": 2}, which of these two expressions raises an error, and why? (1) {a, b} (2) dictfunction(a, b), where dictfunction is any function that accepts **kwargs.
Show answer
Expression 2 raises a TypeError for a repeated keyword argument. Expression 1 is valid and returns {'x': 2}, because dictionary literals let a later key replace an earlier one, while calls reject duplicate keywords.