Skip to main content

Python Dictionaries

Data Types Focus

Python Dictionaries

Dictionaries map keys to values with O(1) lookups on average. Learn how to create, update, iterate, and merge them responsibly.

Creation

user = {"id": "42", "active": True}
config = dict(debug=True, retries=3)

Keys must be hashable. Strings, numbers, and tuples are common choices.

Access

user["id"]
user.get("email", "unknown")

Use get to avoid KeyError when missing keys are acceptable.

Iteration

for key, value in user.items():
...

.keys() and .values() provide views that update automatically as the dict changes.

Merging

merged = {**defaults, **overrides}
# Python 3.9+
merged = defaults | overrides

Later keys override earlier ones.

Next up in your learning path