Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python dict fromkeys: Usage, Pitfalls, and Alternatives

Learn how `dict.fromkeys` works, the shared mutable value pitfall, and when to use a dictionary comprehension instead.

~4 min readPython
#python#dictionary#fromkeys#data-structures
A Python dictionary being created from a list of keys with a single shared value, illustrating the fromkeys method.

The dict.fromkeys method creates a new dictionary from an iterable of keys and a single value. It is a concise way to initialize a dictionary when all keys should share the same initial value. However, its behavior with mutable defaults often surprises developers. This article explains how dict.fromkeys works, where it fails, and when to use an alternative.

How dict.fromkeys Works

The method is a class method on dict, so you call it as dict.fromkeys(iterable, value). It returns a new dictionary where each element of the iterable becomes a key, and every key maps to the same value. If you omit the value, it defaults to None.

python
keys = ['a', 'b', 'c'] d = dict.fromkeys(keys) print(d) # {'a': None, 'b': None, 'c': None} d_with_value = dict.fromkeys(keys, 0) print(d_with_value) # {'a': 0, 'b': 0, 'c': 0}

The iterable can be any iterable, such as a list, tuple, string, set, or generator. For an ordered iterable, keys are inserted in the order they are produced, and Python 3.7+ guarantees that dictionaries preserve insertion order.

The Shared-Value Pitfall

When the value passed to fromkeys is a mutable object—like a list, dict, or set—all keys reference the same object. Mutating that object through one key affects every key. This is a common source of bugs.

python
d = dict.fromkeys(['x', 'y'], []) d['x'].append(1) print(d) # {'x': [1], 'y': [1]}

To give each key its own independent mutable value, use a dictionary comprehension or explicit loop that creates a new object for each key. For example:

python
keys = ['x', 'y'] d = {k: [] for k in keys} d['x'].append(1) print(d) # {'x': [1], 'y': []}

In this comprehension, [] is evaluated separately for each key, creating a fresh list each time. fromkeys evaluates its value argument once and reuses the same object. Note that {k: value for k in keys} would not fix the problem if value is a mutable object; the expression would just return the same value reference for every key.

Using fromkeys for Immutable Defaults

When the default value is immutable—such as an integer, string, tuple, or None—the shared reference is not a problem because immutable objects cannot be modified in place. This makes fromkeys a natural fit for initializing counters, flags, or lookup tables.

python
word_count = dict.fromkeys(words, 0) status = dict.fromkeys(user_ids, 'pending')

These patterns are readable and efficient. The method avoids an explicit loop and clearly communicates that all keys start with the same state.

Performance and Memory Considerations

In CPython, fromkeys is implemented in C, and it can be faster than an equivalent comprehension for large iterables because it avoids a Python-level loop. The actual difference depends on the interpreter, version, and data. fromkeys also stores a single value object reference, which can reduce memory when the value object is reused; this sharing is safe only for immutable values.

If you need independent mutable values, use a comprehension that constructs a new object for each key. The extra allocation is the right trade-off because correctness matters more than a small performance difference.

ApproachValue behaviorUse case
dict.fromkeys(keys, value)Reuses one value object for all keysAll keys start with the same immutable value
{k: [] for k in keys}Creates a new list per keyEach key needs an independent mutable value
{k: [k] for k in keys}Evaluates the value expression per key, so it can depend on the keyDefault value depends on the key

Common Mistakes and Edge Cases

One mistake is assuming fromkeys copies the value for each key. It does not. Another is passing a list as the value and then appending to it, expecting each key to have its own list. As shown earlier, that leads to shared state.

Another edge case involves using a set or a generator as the iterable. Sets do not guarantee order, so the resulting dictionary order may vary. Generators work, but they are consumed once—reusing the same generator for multiple fromkeys calls will not produce the same result.

python
keys = ['a', 'b'] d1 = dict.fromkeys(keys, []) d2 = dict.fromkeys(keys, []) print(d1 is d2) # False print(d1['a'] is d1['b']) # True, shared within each dict

Also note that the value must be passed positionally; fromkeys does not accept keyword arguments.

When Not to Use fromkeys

Avoid fromkeys when you need each key to map to a distinct mutable object. In that case, a dictionary comprehension or loop that creates a fresh object for each key is clearer and safer.

Avoid it when the default value depends on the key. For example, if you want to initialize a dictionary where each key maps to a list that already contains the key itself, you need a comprehension:

python
keys = ['a', 'b'] d = {k: [k] for k in keys} print(d) # {'a': ['a'], 'b': ['b']}

Similarly, if the value must be computed from the key or from external data, fromkeys is not suitable because it accepts a single static value.

For simple immutable defaults, fromkeys is a compact and idiomatic choice. For anything more complex, prefer an explicit construction method. Understanding this boundary prevents subtle bugs and keeps code maintainable.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.