Python Function Reference

dict.fromkeys

Create a dictionary with keys from an iterable and one value for all of them.

Python 3.13
dict.fromkeys(iterable[, value])

Parameters

iterableIterable
The keys of the new dictionary.
valueAnyoptional
The value for all keys, None by default.

Return value

A new dictionary.

Examples

The same value for all keys

Python 3.13
print(dict.fromkeys(['a', 'b'], 0))
{'a': 0, 'b': 0}

Removing duplicates while keeping the order

Python 3.13
print(list(dict.fromkeys([3, 1, 3, 2, 1])))
[3, 1, 2]

A shared list for all keys

Python 3.13
groups = dict.fromkeys(['a', 'b'], [])
groups['a'].append(1)
print(groups)
{'a': [1], 'b': [1]}

Details

All keys get the same value object: if it is a list, a change through one key is visible under all of them. For a separate list per key, use {key: [] for key in keys} or collections.defaultdict(list). Duplicate keys collapse, so list(dict.fromkeys(items)) removes duplicates while keeping the order.

See also