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

← All Python dict methods · String methods · Built-in functions