Dictionary Methods
fromkeys()
Create a new dictionary with keys from an iterable and a shared default value.
dict.fromkeys(iterable, value=None)
dict.fromkeys() is a class method that returns a new dictionary whose keys are taken from iterable and each mapped to value.
If value is omitted, all keys default to None.
Parameters
| Name | Description |
|---|---|
| iterable | An iterable of keys (such as a list, tuple, or set). |
| value | Optional value assigned to each key. Defaults to None. |
Returns
A new dictionary initialized with the specified keys.
Try it
Run it and change it
keys = ["cpu", "memory", "storage"] status = dict.fromkeys(keys, "online") print(status)
Worth knowing
- Mutable value pitfall: If you provide a mutable object (like
dict.fromkeys(keys, [])), all keys will reference the exact same list instance in memory. Use a dict comprehension{k: [] for k in keys}instead for mutable values.