Python Reference ยท Dictionaries and Sets
Python dict.fromkeys() method
Reference for Python dict.fromkeys(): build a dictionary from an iterable of keys with one shared value, the mutable default trap, and removing duplicates.
The dict.fromkeys() class method creates a new dictionary whose keys come from an iterable. Every key gets the same value, which is None unless you pass a second argument.
It is handy for initializing counters or flags, and for removing duplicates while keeping the first-seen order. Its one big trap is that the value is shared: all keys point to the same object, which matters when that object is mutable.
d = dict.fromkeys(["a", "b", "c"], 0) print(d) # {'a': 0, 'b': 0, 'c': 0}
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
dict.fromkeys(iterable, value=None, /)
| Name | Description |
|---|---|
iterable |
The keys. Each item must be hashable. Duplicates collapse into one key. |
value |
Optional. The value stored for every key. Defaults to None. |
Return value: a new dictionary. Keys appear in the order the iterable produced them (first occurrence wins for duplicates).
Raises: TypeError if a key is not hashable or the first argument is not iterable.
Usage notes
- Call it on the class.
dict.fromkeys(...)is the normal form. Calling it on an existing dict,d.fromkeys(...), also builds a new dictionary and does not touchd. - One value object for all keys. For immutable values (numbers, strings,
None, tuples of those) this is harmless. For lists, sets or dicts use a comprehension,{k: [] for k in keys}, so each key gets its own object.collections.defaultdict(list)is another option. - Order-preserving de-duplication.
list(dict.fromkeys(items))removes duplicates and keeps first-seen order, unlikelist(set(items)). - Argument names. Both parameters are positional-only, so
value=0as a keyword fails. - Subclasses. On a subclass such as
collections.OrderedDictorCounter,fromkeys()builds an instance of that subclass (forCounterit is not implemented). - Strings as keys. A string is an iterable of characters, so
dict.fromkeys("abc")creates three keys, not one. Pass["abc"]for a single key. - Missing key defaults.
fromkeys()does not set a default for keys added later. For that, usedict.get()ordefaultdict.