Dictionary fromkeys() Method in Python

Python Dictionary fromkeys() Method

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.

Syntax of the 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:

Example 1: Creating a dictionary with default values using a list of keys

# 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)

Output:

{'a': 0, 'b': 0, 'c': 0}

Example 2: Creating a dictionary with default value using a tuple of keys

# 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)

Output:

{'name': 'unknown', 'age': 'unknown', 'city': 'unknown'}

Example 3: Creating a dictionary with default value using a string as keys

# 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)

Output:

{'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)

Output:

{'x': None, 'y': None, 'z': None}

That's how you can use the fromkeys() method to create dictionaries with default values for specified keys.