Merging dicts with ** ({**a, **b})
Inside braces, `**d` copies every key-value pair of `d` into a new dict.
Used in 37 lessons of the course, from Project 01.
Inside a dict literal, **other means: "put all the pairs of other here". This lets you build a new dict from one or more dicts without touching the originals.
It reads left to right. If a key appears twice, the last one wins. That is why {**defaults, **changes} is a common pattern: defaults go first and your changes override them.
You can also mix ** with normal pairs: {**base, "extra": 1}.
It is written this way because it makes a shallow copy: the new dict is independent, but nested values are still the same objects. In the course you will see it when building config dicts from other ones, like cfg, without modifying the original.
new = {**a, **b}
Reach for it when: you need a new dict based on others, with some values changed, without modifying the originals.
Examples
Common mistake
a = {"n": 1}
b = {"n": 2}
print({**b, **a})Why: Order matters: the last repeated key wins. Here `a` comes last and overrides `b`, maybe the opposite of what you wanted.
How to write it: Put the base values first and the ones that should win last: use {**b, **a} only when a is the one in charge.
Common mistake
a = {"x": 1}
print({**a, **[1, 2]})Why: `**` only works with mappings (dicts). A list has no keys and values to copy.
How to write it: Convert the data to a dict first, for example with dict(zip(keys, values)).
