Introduction: Python Dictionary fromkeys() Method
When working with Python dictionaries, there are times when multiple keys need the same starting value. Creating such dictionaries manually can be repetitive, especially for simple structures.
This is where the Python dictionary fromkeys() method becomes useful.
What it is: The fromkeys() method is a built-in Python dictionary method used to create a new dictionary from a sequence of keys, assigning the same value to all keys at once. If no value is provided, Python assigns None by default.
You can also jump directly to a quick example of the fromkeys() method.
To understand where it fits in real programs, check its real-world use cases.
Next, let’s understand the syntax and parameters of the Python Dictionary fromkeys() method before exploring practical examples.
Tip: Since fromkeys() creates new dictionaries, it is useful to first understand dictionary structure and syntax. See our Python Dictionary Syntax and Concepts Guide.
Syntax, Parameters, Return Value and Examples: Python Dictionary fromkeys() Method
Before using this method in real programs, let’s understand how its syntax and parameters work.
Syntax
dict.fromkeys(iterable, value=None)
Parameters
| Parameter | Description |
|---|---|
| iterable | A sequence of keys such as list, tuple, set, or string |
| value | The value assigned to all keys (default is None) |
The method does not modify the original data and simply returns a new dictionary.
Important Note
If a mutable object (like a list) is used as the value, all keys will share the same reference.
Quick Example
keys = ["name", "age", "city"]
result = dict.fromkeys(keys)
print(result)
# Output:
{'name': None, 'age': None, 'city': None}
Since no value is provided, all keys are automatically assigned None.
How Python Dictionary fromkeys() Works
- The fromkeys() method takes an iterable (like list, tuple, set, or string) and creates a new dictionary by assigning the same value to each key.
- If no value is provided, Python automatically assigns
Noneto all keys. Internally, it does not modify the original data; instead, it returns a new dictionary object containing the generated key-value pairs. - This makes it a convenient way to initialize dictionaries without using loops.
Examples: Dictionary fromkeys() Method
Now let’s understand how fromkeys() works with practical examples.
Example 1: Creating Dictionary with Default None Values
keys = ["name", "age", "city"]
result = dict.fromkeys(keys)
print(result)
# Output:
{'name': None, 'age': None, 'city': None}
Explanation: When no value is given, Python assigns None to all keys automatically.
Example 2: Assigning Same Value to All Keys
keys = ["apple", "banana", "cherry"]
result = dict.fromkeys(keys, 0)
print(result)
# Output:
{'apple': 0, 'banana': 0, 'cherry': 0}
Explanation: All keys are initialized with the same value, useful for counters or tracking values.
Example 3: Using String as Keys Source
keys = "abc"
result = dict.fromkeys(keys)
print(result)
# Output:
{'a': None, 'b': None, 'c': None}
Explanation: Each character in the string becomes a dictionary key.
Example 4: Using Set as Iterable
keys = {"apple", "banana", "cherry"}
result = dict.fromkeys(keys, "fruit")
print(result)
# Possible output:
{'cherry': 'fruit', 'apple': 'fruit', 'banana': 'fruit'}
Explanation: All set elements become keys with the same assigned value.
Note: Since sets are unordered collections, the order of dictionary keys created from a set may vary.
Example 5: Using Range for Numeric Keys
keys = range(3)
result = dict.fromkeys(keys, True)
print(result)
# Output:
{0: True, 1: True, 2: True}
Explanation: Range generates numeric keys, each assigned the same boolean value.
Example 6: Mutable Value Shared Across Keys
keys = ['a', 'b', 'c']
default_list = [1, 2]
result = dict.fromkeys(keys, default_list)
default_list.append(3)
print(result)
# Output:
{'a': [1, 2, 3], 'b': [1, 2, 3], 'c': [1, 2, 3]}
Explanation: All keys share the same list object, so changes affect every key.
Example 7: Safe Alternative Using Dictionary Comprehension
keys = ['a', 'b', 'c']
result = {key: [] for key in keys}
print(result)
# Output:
{'a': [], 'b': [], 'c': []}
Explanation: Each key gets its own independent list, avoiding shared references.
Example 8: Configuration Template
config_keys = ['host', 'port', 'debug']
config = dict.fromkeys(config_keys)
print(config)
# Output:
{'host': None, 'port': None, 'debug': None}
Explanation: A simple structure is created for configuration settings that can be filled later.
Real-World Use Cases: Dictionary fromkeys() Method
Here are some practical situations where the Python Dictionary fromkeys() Method is commonly used:
- Initialize dictionaries with default values
- Create counters or flags for multiple keys
- Build configuration or settings templates
- Generate placeholder dictionaries before processing data
- Avoid writing repetitive code when assigning the same value to multiple keys
Key Takeaways: Dictionary fromkeys() Method
Before wrapping up, let’s quickly summarize the most important concepts discussed in this Python Dictionary fromkeys() Method tutorial:
- Creates a dictionary from a sequence of keys
- Assigns the same value to all keys
- Defaults to None if no value is provided
- Helps avoid loops for simple initialization
- Be careful with mutable objects (shared reference issue)
- Dictionary comprehension is better for independent values
Overall, Python dictionary fromkeys() method is a convenient way to initialize dictionaries, but it should be used carefully when working with mutable data types.