Python Dictionaries
Key-value mappings for fast lookups, updates, and nested data
Overview
Dictionaries (dict) store key-value pairs with O(1) average lookup time. Keys must be hashable (strings, numbers, tuples of hashables). Dicts preserve insertion order as of Python 3.7+ and are ideal for records, caches, and configuration.
Syntax / Usage
# Create
user = {"name": "Ada", "role": "engineer", "active": True}
empty = {}
from_keys = dict.fromkeys(["a", "b"], 0)
# Access and update
user["name"] # "Ada"
user.get("email", "n/a") # safe default
user["email"] = "ada@example.com"
# Iterate
for key in user:
print(key, user[key])
for key, value in user.items():
print(key, value)
# Merge (Python 3.9+)
defaults = {"theme": "dark"}
prefs = {"lang": "en"}
merged = defaults | prefs
Examples
Count word frequency in a sentence:
sentence = "the cat sat on the mat"
counts = {}
for word in sentence.split():
counts[word] = counts.get(word, 0) + 1
# {'the': 2, 'cat': 1, 'sat': 1, 'on': 1, 'mat': 1}
Build a lookup table from a list of records:
users = [{"id": 1, "name": "Ada"}, {"id": 2, "name": "Guido"}]
by_id = {u["id"]: u for u in users}
by_id[1]["name"] # "Ada"
Common Mistakes
- Using mutable types (lists) as dict keys
- Assuming
dict[key]returnsNonefor missing keys—it raisesKeyError - Relying on order before Python 3.7 in older codebases
- Shallow copying nested dicts when a deep copy is needed
See Also
python-tuples python-sets python-list-comprehension