The fromkeys()
method in Python dictionaries is used to create a new dictionary with specified keys and default values for those keys. This method allows you to create a dictionary where all the keys have the same initial value, which you can specify as an argument to the fromkeys()
method. It is a convenient way to initialize a dictionary with default values.
fromkeys()
method:
new_dict = dict.fromkeys(keys, value)
keys
: It is an iterable (e.g., a list, tuple, or string) containing the keys that you want to include in the new dictionary.value
: (Optional) It represents the default value that will be associated with each key in the new dictionary. If not provided, the default value will be None
.Now, let's see some examples:
# Create a new dictionary with default value 0 for keys 'a', 'b', and 'c'
new_dict = dict.fromkeys(['a', 'b', 'c'], 0)
# Print the new dictionary
print(new_dict)
{'a': 0, 'b': 0, 'c': 0}
# Create a new dictionary with default value 'unknown' for keys 'name', 'age', and 'city'
new_dict = dict.fromkeys(('name', 'age', 'city'), 'unknown')
# Print the new dictionary
print(new_dict)
{'name': 'unknown', 'age': 'unknown', 'city': 'unknown'}
# Create a new dictionary with default value False for keys 'a', 'b', 'c', and 'd'
new_dict = dict.fromkeys("abcd", False)
# Print the new dictionary
print(new_dict)
{'a': False, 'b': False, 'c': False, 'd': False}
If you omit the value
argument, as mentioned earlier, the default value for keys will be None
.
# Create a new dictionary with default value None for keys 'x', 'y', 'z'
new_dict = dict.fromkeys(['x', 'y', 'z'])
# Print the new dictionary
print(new_dict)
{'x': None, 'y': None, 'z': None}
That's how you can use the fromkeys()
method to create dictionaries with default values for specified keys.