all Python 3Dictionaries (dict)function
dict.fromkeys()
iteration
Creates a new dictionary from an iterable of keys. The second argument sets the same default value for every key (None by default).
Syntax
dict.fromkeys(iterable, value=None)
The value is evaluated once and shared by every key rather than copied per key: pass an empty list as the second argument and appending through one key changes it for all of them. For mutable values use a dict comprehension or defaultdict instead. A side use that comes up constantly: calling it with a single argument drops duplicates from a sequence while preserving first-occurrence order.
Examples
print(dict.fromkeys(["a","b","c"])) # → {'a': None, 'b': None, 'c': None}
print(dict.fromkeys("xyz", 0)) # → {'x': 0, 'y': 0, 'z': 0}
keys = ["name","age","city"]
d = dict.fromkeys(keys, "N/A")
print(d) # → {'name': 'N/A', 'age': 'N/A', 'city': 'N/A'}
print(dict.fromkeys([1,2,1,3])) # → {1: None, 2: None, 3: None}
See also
Open in the full glossarydocs.python.orgReport an inaccuracy