In Python, there are several ways to create a dictionary.
One of them is by calling the class method
dict.fromkeys(iterable, value).
This approach is convenient when you want to initialize a dictionary and assign the same value to all its keys at once.
The method’s first argument should be an iterable object whose elements become the dictionary’s keys.
The second argument provides the single value associated with each of those keys.
There’s an important detail to be aware of: this value is shared among all keys.
In other words, every key in the dictionary will reference this same object.
If that object happens to be mutable — for example, a list, set, or dictionary — then modifying it through one key will affect all the others.
If you don’t realize this, the behavior of your dictionary can come as quite a surprise.
Let’s take an example.
|
1 2 3 4 5 6 7 8 9 |
d = dict.fromkeys('abc', set()) print(d) # Output: {'a': set(), 'b': set(), 'c': set()} d['a'].add(123) print(d) # Output: {'a': {123}, 'b': {123}, 'c': {123}} |
As you can see, when we added an element to the set referenced by ‘a’, the change appeared in the sets associated with all the other keys. That’s because all the keys refer to the same set object.
If you want to avoid this shared-reference behavior, you can use a dictionary comprehension instead, which creates an independent set object for each key:
|
1 2 3 4 5 6 7 8 9 |
dd = {k: set() for k in 'abc'} print(dd) # Output: {'a': set(), 'b': set(), 'c': set()} dd['a'].add(123) print(dd) # Output: {'a': {123}, 'b': set(), 'c': set()} |
Now each key has its own separate set, so modifying one doesn’t affect the others.
Key Takeaways
- dict.fromkeys() associates the same value to every key.
- If that object is immutable (like an int, string, or tuple), there’s no issue.
- But if it’s mutable (like a list, set, or dict), all keys will share changes to that single object.
- To give each key its own independent mutable object, use a dictionary comprehension or a loop instead.
If you want to learn more about dictionaries and their methods, consult the chapters “Built-in container objects” and “Public methods of built-in types” in the e-book Python Knowledge Building Step by Step.