Python Dictionary fromkeys() Method
dict.fromkeys(keys, value=None) is a class method that builds a new dictionary whose keys come from keys, all given the same value (None by default).fromkeys() is the quick way to create a dictionary skeleton: a counter per letter that starts at zero, a set of flags all set to False, or a list of keys with placeholders to fill in later. It belongs to the group of dictionary methods but is called on dict itself, not on an existing dictionary.
One warning before you use it: every key shares the same value object. That is harmless for numbers, strings and None, and a classic trap for lists. If your values come from separate lists, see converting two lists to a dictionary.
| Syntax | dict.fromkeys(iterable) or dict.fromkeys(iterable, value) |
|---|---|
| Parameters | iterable: the keys; value: the value for every key (optional, default None) |
| Returns | A new dictionary |
| Duplicate keys | Appear once in the result |
| Time complexity | O(n) |
How dict.fromkeys() builds a dictionary
You call it on the dict class. Each element of the iterable becomes a key, and each key is paired with the one value you provide. Duplicate keys collapse into one entry, and the keys keep the order in which they first appear.
letters = dict.fromkeys("abca", 0)
print(letters)
flags = dict.fromkeys(["read", "write"], False)
print(flags)
print(dict.fromkeys([1, 2, 3]))The shared mutable value trap
The value is not copied for each key, so all keys point at one object. With an immutable value (number, string, None, tuple) this is fine because you replace values instead of changing them. With a list or dictionary, appending through one key changes what every key sees.
bad = dict.fromkeys(["a", "b"], [])
bad["a"].append(1)
print(bad)
good = {key: [] for key in ["a", "b"]}
good["a"].append(1)
print(good)When each key needs its own list, use a dictionary comprehension, as shown in the second half.
Removing duplicates while keeping order
Because dictionary keys are unique and ordered, list(dict.fromkeys(items)) is a well-known way to remove duplicates from a list while keeping the first occurrence of each item. A set also removes duplicates but does not preserve order.
fromkeys() compared with other ways to build a dictionary
| Goal | Code | Result |
|---|---|---|
| Same value for every key | dict.fromkeys(["a", "b"], 0) | {'a': 0, 'b': 0} |
| Separate list per key | {k: [] for k in keys} | Each key has its own list |
| Pair two lists | dict(zip(keys, values)) | {'a': 1, 'b': 2} |
Keys with None placeholders | dict.fromkeys(keys) | {'a': None, 'b': None} |
Examples you can run
Press Run, then edit the code and run it again.
Start every counter at zero
A dictionary with all counts ready to be incremented with +=.
votes = dict.fromkeys(["red", "green", "blue"], 0)
votes["red"] += 1
votes["blue"] += 2
print(votes)Expected output{'red': 1, 'green': 0, 'blue': 2}
Remove duplicates but keep order
The first occurrence of each item wins and the order is preserved.
tags = ["python", "dict", "python", "list", "dict"]
unique = list(dict.fromkeys(tags))
print(unique)Expected output['python', 'dict', 'list']
Keys from a range
Any iterable works as the source of keys. Without a value, each key gets None.
slots = dict.fromkeys(range(1, 4))
print(slots)
slots[2] = "booked"
print(slots)Expected output{1: None, 2: None, 3: None}
{1: None, 2: 'booked', 3: None}
Common mistakes
Using a list as the shared value
✗ Wrong
inbox = dict.fromkeys(["asha", "ravi"], [])
inbox["asha"].append("hi")
print(inbox)✓ Right
inbox = {k: [] for k in ["asha", "ravi"]}
inbox["asha"].append("hi")
print(inbox)Build the dictionary with a comprehension so each key gets its own list: {k: [] for k in names}.
Calling fromkeys() on an existing dictionary and expecting it to change it
✗ Wrong
d = {"a": 1}
d.fromkeys(["b", "c"], 0)
print(d)✓ Right
d = {"a": 1}
d.update(dict.fromkeys(["b", "c"], 0))
print(d)fromkeys() returns a new dictionary. Assign it, or merge it in with update().
Python Dictionary fromkeys() Method: questions people ask
What does dict.fromkeys() do in Python?
It creates a new dictionary with the items of an iterable as keys and one shared value (default None) for all of them.
Why do all keys share the same list in fromkeys()?
Because the value is evaluated once and the same object is stored under every key. Use a dictionary comprehension to give each key its own list.
How do I remove duplicates from a list in order?
Use list(dict.fromkeys(my_list)). It keeps the first occurrence of each item and preserves the original order.
Keep learning
Step-by-step lessons:
Python DictionariesPython Dictionary Methods
Related:
How to Convert a List to a Dictionary in PythonPython Dictionary setdefault() MethodPython Dictionary update() MethodPython Dictionary copy() Method
More in dictionary methods:
Python Dictionary get() MethodPython Dictionary items() MethodPython Dictionary keys() MethodPython Dictionary values() MethodPython Dictionary update() MethodPython Dictionary pop() MethodPython Dictionary popitem() MethodPython Dictionary setdefault() Method See all →