Python Dictionary fromkeys()
The fromkeys()
method creates a new dictionary with specified keys from a given iterable (like a list, tuple, or string) and assigns a single default value to all those keys.
Syntax
dict.fromkeys(iterable, value)
Parameters
iterable
: A sequence of keys (e.g. list, tuple, or string).
value
(Optional) : The value to be assigned to all keys (default is None
).
Return Value
It returns a new dictionary where each key from the given iterable is mapped to the specified value (default is None
).
Example: Creating a dictionary with a specific default value
keys = ['a', 'b', 'c']
default_value = 10
new_dict = dict.fromkeys(keys, default_value)
print(new_dict) # Output: {'a': 10, 'b': 10, 'c': 10}
Example: Creating a dictionary with None as the default value
If no default value is provided, all keys will be mapped to None
.
keys = ['a', 'b', 'c']
new_dict = dict.fromkeys(keys)
print(new_dict) # Output: {'a': None, 'b': None, 'c': None}
Example: Creating a dictionary with mutable object as the default value
You need to be careful when using mutable objects (like lists) as the value because all keys will reference the same object. Modifying the value associated with one key will affect all other keys because they are all referencing the same object in memory.
keys = ['a', 'b', 'c']
default_value = []
new_dict = dict.fromkeys(keys, default_value)
print(new_dict) # Output: {'a': [], 'b': [], 'c': []}
new_dict['a'].append(5)
print(new_dict) # Output: {'a': [5], 'b': [5], 'c': [5]}
If you need each key to have its own independent mutable value, you can use dictionary comprehension to assign a separate mutable object for each key.
keys = ['a', 'b', 'c']
new_dict = {key:[] for key in keys}
print(new_dict) # Output: {'a': [], 'b': [], 'c': []}
new_dict['a'].append(5)
print(new_dict) # Output: {'a': [5], 'b': [], 'c': []}