dict.fromkeys()
Builds a new dictionary whose keys come from a list or other iterable, all set to the same value (None by default).
dict.fromkeys(iterable, value=None, /)dict.fromkeys(keys, value) creates a dictionary in one step: every key from keys, each with the same starting value. It is called on the class itself, dict.fromkeys(...), not on an existing dictionary.
Use it to start counters at 0, mark every item as not done yet, or remove duplicates from a list while keeping the order: list(dict.fromkeys(items)).
The big trap: every key gets the very same value object. With a number or a string that is fine. With a list or a dictionary as the value, all keys share one list, so appending for one key appends for all. Use a dictionary comprehension instead.
Parameters
| Parameter | What it is |
|---|---|
iterablerequired | The keys: a list, tuple, string, range or any other iterable. Repeated keys appear only once. |
valueoptional, default None | The value given to every key. The same object is used for all keys. Give it by position: value=0 raises TypeError. |
Return value
A new dictionary.
Examples
1Start every counter at 0
colors = ["red", "green", "blue"]
counts = dict.fromkeys(colors, 0)
counts["red"] += 1
print(counts){'red': 1, 'green': 0, 'blue': 0}2Without a value, every key gets None
fields = dict.fromkeys(["name", "email", "phone"])
print(fields){'name': None, 'email': None, 'phone': None}3Remove duplicates and keep the order
visits = ["home", "shop", "home", "cart", "shop"]
unique = list(dict.fromkeys(visits))
print(unique)['home', 'shop', 'cart']
set(visits) also removes duplicates but loses the order; a dictionary keeps the order of first appearance.
4A checklist for a trip
packed = dict.fromkeys(["passport", "charger", "tickets"], False)
packed["passport"] = True
missing = [item for item, done in packed.items() if not done]
print("Still to pack:", missing)Still to pack: ['charger', 'tickets']
Common mistakes
Using a list as the shared value
All keys point to one and the same list. Appending through one key changes what every key sees. Build a fresh list per key with a comprehension.
groups = dict.fromkeys(["a", "b"], [])
groups["a"].append(1)
print(groups)
groups = {k: [] for k in ["a", "b"]}
groups["a"].append(1)
print(groups){'a': [1], 'b': [1]}
{'a': [1], 'b': []}Expecting it to change an existing dictionary
fromkeys() always returns a new dictionary. d.fromkeys(...) works but ignores d completely, which is confusing; write dict.fromkeys(...).
Questions people ask
How do I create a dictionary from a list of keys?
dict.fromkeys(keys, value) when every key gets the same simple value; {k: f(k) for k in keys} when each key needs its own value or a new list.
How do I create a dictionary from two lists?
Use zip(): dict(zip(keys, values)).
How do I remove duplicates from a list but keep the order?
list(dict.fromkeys(items)).