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
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 beNone
.
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
2. Specifying a Value
3. Using a Tuple as Keys
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:
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.