The method dict.fromkeys()
is a very useful method for creating new dictionaries from a given iterable of keys.
Definition: dict.fromkeys()
is a method that inputs keys and maybe an optional value, and outputs a dictionary with the specified keys, that are mapped either to optionally specified values or to the default None
value.
dict.fromkeys() Syntax
Method declaration:
dict.fromKeys(keys, optional_value)
Parameter Arguments:
keys | required input | Iterable input specifying the keys of the newly made dictionary |
optional_value | optional input | Specified value assigned to every key in the dictionary, the default optional value is None . |
Examples of dict.fromkeys() Method
Next, we’re going to examine three examples of the dict.fromkeys()
method.
Example 1
The following is an example of an ordered integers dictionary, with and without an optional value.
# Initializing a number sequence: sequence = {1, 2, 3, 4, 5} # Use the dict.fromKeys() method to convert the sequence to a dictionary: # Initializing with default None value: result_dict = dict.fromkeys(sequence) print('newly made dictionary with default None values: ', result_dict) # Initializing another dictionary, with an optional value, 1 in this case: result_dict2 = dict.fromkeys(sequence, 1) print('2nd dictionary with 1 as the specified value: ', result_dict2)
This is the output of the previous code snippet:
newly made dictionary with default None values: {1: None, 2: None, 3: None, 4: None, 5: None} 2nd dictionary with 1 as the specified value: {1: 1, 2: 1, 3: 1, 4: 1, 5: 1}
Example 2
The following is an example of adding a specified default value:
a = ('key_1', 'key_2', 'key_3') b = 7 default_dict = dict.fromkeys(a, b) print(default_dict) # {'key_1': 7, 'key_2': 7, 'key_3': 7}
Example 3
The following is an example of setting an empty dictionary {}
as the default value to the dict.fromKeys()
method:
new_dict = dict.fromkeys(range(5), {}) print('a new dictionary with empty dictionaries as values: ', new_dict) # a new dictionary with empty dictionaries as values: {0: {}, 1: {}, 2: {}, 3: {}, 4: {}}