Python dict.fromkeys() function


The dict.fromkeys() method in Python is a class method that creates a new dictionary from a given sequence of keys. This method allows you to initialize all keys in the new dictionary with a specified value. If no value is provided, the keys will be set to None by default.

Syntax

dict.fromkeys(seq[, value])
  • seq: A sequence (like a list or tuple) that contains the keys you want to use for the new dictionary.
  • value (optional): The value to set for all keys in the new dictionary. If not provided, the default value will be None.

Return Value

  • The dict.fromkeys() method returns a new dictionary with the specified keys and their corresponding values.

Example

Here are some examples to illustrate how dict.fromkeys() works:

1. Basic Example

# Sequence of keys keys = ['a', 'b', 'c'] # Creating a dictionary with default value of None new_dict = dict.fromkeys(keys) print(new_dict) # Output: {'a': None, 'b': None, 'c': None}

2. Specifying a Value

# Sequence of keys keys = ['a', 'b', 'c'] # Creating a dictionary with a specified value new_dict_with_value = dict.fromkeys(keys, 0) print(new_dict_with_value) # Output: {'a': 0, 'b': 0, 'c': 0}

3. Using a Tuple as Keys

# Tuple of keys keys_tuple = ('x', 'y', 'z') # Creating a dictionary from the tuple with a specified value tuple_dict = dict.fromkeys(keys_tuple, 'default') print(tuple_dict) # Output: {'x': 'default', 'y': 'default', 'z': 'default'}

Important Note on Mutable Values

If you use a mutable value (like a list or dictionary) as the second argument, all keys will refer to the same object. This means that if you modify the value for one key, it will affect all the keys.

Example of Mutable Value:

# Using a mutable value mutable_value_dict = dict.fromkeys(['a', 'b', 'c'], []) # Modifying the list for one key mutable_value_dict['a'].append(1) print(mutable_value_dict) # Output: {'a': [1], 'b': [1], 'c': [1]} # All keys share the same list

Use Cases

  • Creating Default Dictionaries: Useful for initializing dictionaries where all keys should start with the same value.
  • Data Structure Initialization: Helpful when setting up data structures that will be populated later.
  • Quick Setup: Provides a quick and efficient way to create dictionaries from lists or tuples.

Summary

The dict.fromkeys(seq[, value]) method is a convenient way to create a new dictionary with specified keys and optional values in Python. It allows for easy initialization and setup of dictionaries, making it a useful tool in various programming scenarios.