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
| Parameter | Description |
|---|---|
iterable |
The keys. |
value optional |
The value for every key. Default: None |
Return value
A new dict.
Examples
print(dict.fromkeys(["a", "b", "c"], 0))
print(dict.fromkeys("xy"))
Output
{'a': 0, 'b': 0, 'c': 0}
{'x': None, 'y': None}items = ["b", "a", "b", "c", "a"]
print(list(dict.fromkeys(items))) # remove duplicates, keep order
Output
['b', 'a', 'c']
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
| Version | Change |
|---|---|
| Python 3.0 | Added |
Related
dict.setdefault()· Return the value for a key; if the key is missing, insert it with a default value first and return that.dict()· Create a dictionary: a mapping of keys to values. Build it from keyword arguments, pairs or another mapping.- Python Dictionaries · tutorial