merge
dict.fromkeys
Class method that builds a new dict whose keys come from iterable and whose values are all set to value (default None). The same value object is shared across every key — beware mutable defaults.
dict.fromkeys(iterable[, value]) Parameters
| Parameter | Purpose |
|---|---|
| iterable | Any iterable providing the keys |
| value | Value assigned to every key (defaults to None) |
Examples
>>> dict.fromkeys(['a', 'b', 'c'])
{'a': None, 'b': None, 'c': None} Default value is None
>>> dict.fromkeys(range(3), 0)
{0: 0, 1: 0, 2: 0} Initialize a counter-style dict
>>> d = dict.fromkeys(['a', 'b'], [])
>>> d['a'].append(1)
>>> d
{'a': [1], 'b': [1]} GOTCHA — the SAME list is shared by every key
>>> dict.fromkeys('abca')
{'a': None, 'b': None, 'c': None} Duplicate keys in the iterable collapse to one entry
Gotcha
Mutable defaults (list, dict, set) are shared across all keys — use a dict comprehension {k: [] for k in keys} instead. Duplicate keys in the iterable silently deduplicate.
Related methods
dict.setdefault
If key is in the dictionary, returns its value. If not, inserts key with a value of default (None if omitted) and returns default.
dict.copy
Returns a shallow copy of the dictionary — a new dict object with the same key-value pairs. Values themselves are not copied, so nested mutable objects are still shared between the original and the copy.
dict.update
Updates the dictionary in place with key/value pairs from other, overwriting existing keys. Accepts another mapping, an iterable of key/value pairs, and/or keyword arguments; returns None.
dict1 | dict2
Merge operator (Python 3.9+) that returns a new dict containing the entries of d1 followed by d2, with d2's values winning on shared keys. Both operands must be dicts; neither is mutated.
dict1 |= dict2
In-place merge operator (Python 3.9+) that updates d1 with entries from other, with other's values winning on shared keys. Unlike |, the right operand can be any iterable of pairs or a mapping — matching update()'s flexibility.
← All Python dict methods · String methods · Built-in functions