Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

Dictionary unpacking: `{**a, **b}`

Merge defaults and overrides into a new dictionary. When both inputs contain the same key, the value from the right wins.

Version: Python 3.12

Syntax

{**a, **b}

With dictionary unpacking {**a, **b}, each ** inserts key–value pairs from a mapping into a new dict. Entries from a go in first, then entries from b. If both inputs contain a key, b replaces its value without moving the key. Put defaults on the left and overrides on the right.

The operands must be mappings, such as dictionaries. A plain list of key–value pairs is not enough: unpacking it this way raises TypeError. Keys must be hashable but need not be strings. This syntax was introduced in Python 3.5; in Python 3.12, dictionary insertion order is guaranteed.

The merge itself does not change entries in a or b, unlike a.update(b), which changes a in place. The merge is shallow: nested dictionaries are not merged recursively, and retained mutable values are still shared with their source.

Do not confuse this with f(**a, **b). In a function call, keys passed through ** must be strings, and a repeated keyword name raises TypeError rather than replacing the earlier value.

Examples

defaults = {"timeout": 30, "retries": 3}
overrides = {"timeout": 10, "verbose": True}
settings = {**defaults, **overrides}

print(settings)
print(defaults["timeout"])

Result

{'timeout': 10, 'retries': 3, 'verbose': True}
30

`timeout` takes the value `10` from `overrides`, `retries` carries over from `defaults`, and `verbose` is a new entry. The second line shows that `timeout` is still `30` in `defaults`.

Related lessons

  • Python · Lesson 18 · Intermediate · Version: 3

Sources