Creates a new dictionary with default value
Usage
The fromkeys()
method creates a new dictionary with default value for all specified keys.
If default value is not specified, all keys are set to None.
Syntax
dict.fromkeys(keys,value)
Parameter | Condition | Description |
keys | Required | An iterable of keys for the new dictionary |
value | Optional | The value for all keys. Default value is None. |
Examples
# Create a dictionary and set default value 'Developer' for all keys
D = dict.fromkeys(['Bob', 'Sam'], 'Developer')
print(D)
# Prints {'Bob': 'Developer', 'Sam': 'Developer'}
If default value argument is not specified, all keys are set to None.
D = dict.fromkeys(['Bob', 'Sam'])
print(D)
# Prints {'Bob': None, 'Sam': None}
Equivalent Method
Dictionary comprehensions are also useful for initializing dictionaries from keys lists, in much the same way as the fromkeys()
method.
# As if default value is specified
L = ['Bob', 'Sam']
D = {key:'Developer' for key in L}
print(D)
# Prints {'Bob': 'Developer', 'Sam': 'Developer'}
# As if default value is not specified
L = ['Bob', 'Sam']
D = {key:None for key in L}
print(D)
# Prints {'Bob': None, 'Sam': None}