Python Dictionary fromkeys() Method

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)

Python dictionary fromkeys() method parameters
ParameterConditionDescription
keysRequiredAn iterable of keys for the new dictionary
valueOptionalThe value for all keys. Default value is None.

Examples

Example: Create a dictionary and set default value ‘Developer’ for all keys

D = dict.fromkeys(['Bob', 'Sam'], 'Developer')
print(D)    # {'Bob': 'Developer', 'Sam': 'Developer'}

If default value argument is not specified, all keys are set to None.

Example: Create a dictionary without specifying a default value

D = dict.fromkeys(['Bob', 'Sam'])
print(D)    # {'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.

Example:

As if default value is specified

L = ['Bob', 'Sam']
D = {key:'Developer' for key in L}
print(D)    # {'Bob': 'Developer', 'Sam': 'Developer'}

As if default value is not specified

L = ['Bob', 'Sam']
D = {key:None for key in L}
print(D)    # {'Bob': None, 'Sam': None}