Dict Methods
dict.fromkeys()
Creates a dictionary from an iterable of hashable keys. Repeated equal keys occupy one entry; first insertion determines its position. Every entry receives the same value object, not a new copy. If separate mutable values are needed, construct them individually with a dictionary comprehension. The class method also works when called through an instance; the original dictionary is not modified.
Formal Syntax & Structure
python syntaxpython
dict.fromkeys(iterable, value=None, /)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| iterable | Iterable[Hashable] | Source of keys. |
| value | object | Shared value for every key; defaults to None. |
Return Value
dict
New mapping (subclasses may construct subclass instances).
Working Example
Example Snippetpython
shared = dict.fromkeys(["red", "blue"], [])shared["red"].append(1)print(shared)separate = {color: [] for color in ("red", "blue")}separate["red"].append(1)print(separate)