Python 3 reference · Dictionary Methods

Python Dictionary fromkeys() Method

Create a new dictionary with the given keys, all set to the same value (None by default).

Python 3 Since 3.0

Syntax

dict.fromkeys(iterable, value=None)

Parameters

ParameterDescription
iterable The keys.
value optional The value for every key. Default: None

Return value

A new dict.

Examples

Create keys with a defaultTry it yourself
print(dict.fromkeys(["a", "b", "c"], 0))
print(dict.fromkeys("xy"))

Output

{'a': 0, 'b': 0, 'c': 0}
{'x': None, 'y': None}
Remove duplicates in orderTry it yourself
items = ["b", "a", "b", "c", "a"]
print(list(dict.fromkeys(items)))  # remove duplicates, keep order

Output

['b', 'a', 'c']
Careful with mutable valuesTry it yourself
bad = dict.fromkeys(["x", "y"], [])
bad["x"].append(1)
print(bad)  # one shared list!
good = {k: [] for k in ["x", "y"]}
good["x"].append(1)
print(good)

Output

{'x': [1], 'y': [1]}
{'x': [1], 'y': []}

Version history

VersionChange
Python 3.0Added