Python dict for fast key lookups and defaults
A Python dict maps hashable keys to values for fast lookup by key.
Use it when each item has a unique identifier and you need quick access by that key.
The dict.get lets you supply a default for missing keys to keep lookups safe.
This makes dicts a clean fit for key-based lookup tasks.
Python Dict Example For Key Lookup
Output:
Output will appear here...
Output:
user_2: Noah
user_3: unknown
How This Example Works
- The dict literal creates a mapping from user IDs to names; dict keys must be hashable, so strings are a safe choice.
name_by_id["user_2"]returns the value for an existing key, but this form raisesKeyErrorwhen the key is missing.getreturns the provided default when the key is absent, which avoids the exception for optional keys.
Common Mistakes
Mistake: Using d[key] when the key is optional.
Wrong:
status = status_by_order[order_id]
Right:
status = status_by_order.get(order_id, "not found")
Why it happens: d[key] raises KeyError for missing keys, while get returns a default when the key is absent.
Mistake: Using an unhashable key like a list.
Wrong:
bad_key = ["A101"]
status_by_order[bad_key] = "shipped"
Right:
good_key = ("A101",)
status_by_order[good_key] = "shipped"
Why it happens: dict keys must be hashable, and lists are not; tuples work because they are hashable when their contents are hashable.
Mistake: Assuming 1, 1.0, and True are distinct keys.
Wrong:
d = {1: "one", True: "bool"}
Right:
d = {1: "one", 2: "two"}
Why it happens: keys that compare equal index the same dictionary entry, so later assignments overwrite earlier ones.
Python dict vs list: which to use
| Use dict when… | Use list when… |
|---|---|
| You need to map a key to a value and look it up by that key. | You just need an ordered sequence of items or positional access. |
| Keys are stable identifiers like IDs, codes, or names. | The position of each item is the primary way you access it. |
Rule of thumb: use a dict for key-based lookup, and a list for ordered, index-based access.
Performance Considerations
Python’s dict implementation is finely tuned and performs very well as a general-purpose mapping, which is why it is the default choice for repeated key lookups.
If you only need ordered, index-based access, a list can be simpler because dictionaries are indexed by keys rather than positions.
When iterating over dict view objects, avoid adding or deleting entries during the loop; mutation while iterating can raise RuntimeError, so copy the keys first when you need to change them.
More Examples
Merge defaults with overrides (Python 3.9+):
defaults = {"retries": 2, "timeout": 5}
overrides = {"timeout": 10}
config = defaults | overrides
print(config)
| creates a new dict and, when keys overlap, the right-hand dict wins, which is useful for layered settings.
Build a dict from key/value pairs:
language_labels = [("en", "Hello"), ("es", "Hola")]
labels_by_locale = dict(language_labels)
print(labels_by_locale)
dict() accepts an iterable of key/value pairs, which is handy when your data arrives as tuples.
When to Use Python dict
- You need to fetch or update values by a stable key, such as IDs, codes, or names.
- You want predictable iteration order that matches insertion order.
- You need safe defaults for missing keys with
getor explicit key checks. - You need to combine dictionaries with clear precedence rules.
- Do not use a dict if you only need positional access to ordered items; a list is simpler for that case.