A Python dictionary (dict) stores data as key: value pairs inside curly braces {}, giving you instant lookups by key name. Since Python 3.7, dictionaries preserve the exact order in which keys were inserted.
Dictionary keys must be unique and hashable (such as strings, numbers, or tuples), while values can be any Python object including nested lists or other dictionaries.
Using user["role"] raises KeyError when "role" is missing. Calling user.get("role", "guest") safely returns a fallback value instead.
user = {"id": 101, "name": "Farhan", "plan": "starter"}
extra = {"plan": "pro", "verified": True}
# Safe lookup and Python 3.9+ merge operator
role = user.get("role", "member")
merged = user | extra
for key, value in merged.items():
print(f"{key}: {value}")
You can construct or transform dictionaries concisely with a dictionary comprehension instead of filling an empty dict inside a multi-line for loop. When keys might be missing, .setdefault() or collections.defaultdict also avoids repetitive membership checks.
scores = {"alice": 88, "bob": 52, "carol": 94}
passed = {name: score for name, score in scores.items() if score >= 60}
print(passed) # {'alice': 88, 'carol': 94}
d[key]: Prefer d.get(key) when a key might not exist, or handle KeyError explicitly.for k in d: raises RuntimeError; iterate over list(d.keys()) instead.TypeError; convert composite keys to tuples first..keys(), .values(), and .items()?.keys() iterates over keys, .values() iterates over values, and .items() yields (key, value) pairs for unpacking in loops.
Use collections.Counter(items) or counts[key] = counts.get(key, 0) + 1 to avoid manual if key in counts checks.
merged = a | b modify dictionary a?No. The | operator returns a new dictionary, while a |= b updates a in place.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.