Dictionaries are Python's hash maps — the workhorse for any "look up a value by a key" problem. They're ordered (insertion order preserved since Python 3.7), mutable, and rely on hashable keys. If you've used JSON, you've already used dicts.
Creating dictionaries
# Literal — most commonuser = {"name": "Aanya", "age": 28, "city": "Noida"}# Empty dictempty = {}empty2 = dict()# From keyword argumentsuser2 = dict(name="Karan", age=32, city="Bengaluru")# From a list of pairsuser3 = dict([("name", "Meera"), ("age", 24)])# From two parallel lists with zip()keys = ["name", "age", "city"]vals = ["Vikram", 30, "Mumbai"]user4 = dict(zip(keys, vals))
Accessing values
user = {"name": "Aanya", "age": 28}# Bracket access — raises KeyError if missingprint(user["name"]) # Aanya# .get() — returns None if missing, no errorprint(user.get("city")) # Noneprint(user.get("city", "Noida")) # Noida — default value# Membership checkprint("age" in user) # Trueprint("salary" in user) # False
Add · update · delete
user = {"name": "Aanya", "age": 28}# Add or update — same syntaxuser["city"] = "Noida" # adduser["age"] = 29 # updateuser.update({"role": "Analyst", "salary_lpa": 12.4})# Deletedel user["salary_lpa"]removed = user.pop("role") # also returns the valuelast = user.popitem() # removes & returns last inserted (key, value)user.clear() # empties the dict
Useful methods
| Method | Returns |
|---|---|
| d.keys() | view of all keys |
| d.values() | view of all values |
| d.items() | view of (key, value) tuples |
| d.get(k, default) | value or default — no KeyError |
| d.setdefault(k, default) | get if exists, else set then return |
| d.update(other) | merge other into d (in place) |
| d.pop(k) | remove and return value |
| d | other (3.9+) | new dict with merged keys |
a = {"x": 1, "y": 2}b = {"y": 99, "z": 3}# Merge with | (Python 3.9+) — values in b win on collisionmerged = a | bprint(merged) # {'x': 1, 'y': 99, 'z': 3}# In-place merge with |=a |= bprint(a) # {'x': 1, 'y': 99, 'z': 3}
Iterating over a dict
scores = {"Aanya": 92, "Karan": 87, "Meera": 95}# Default — iterates over keysfor name in scores:print(name)# Values onlyfor score in scores.values():print(score)# Most useful: items() — both at oncefor name, score in scores.items():print(f"{name}: {score}")
Dict comprehensions
# Squares of 0-4 keyed by the numbersquares = {n: n * n for n in range(5)}# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}# Filter — keep passing scores onlyscores = {"Aanya": 92, "Karan": 47, "Meera": 95}passing = {name: s for name, s in scores.items() if s >= 60}# {'Aanya': 92, 'Meera': 95}# Invert a dict — values become keyscodes = {"in": 91, "us": 1, "uk": 44}flipped = {v: k for k, v in codes.items()}# {91: 'in', 1: 'us', 44: 'uk'}
Nested dictionaries
# A common shape — JSON-like dataorder = {"id": 1042,"customer": {"name": "Aanya", "email": "aanya@x.com"},"items": [{"sku": "P1", "qty": 2, "price": 199},{"sku": "P2", "qty": 1, "price": 1499}]}print(order["customer"]["name"]) # Aanyaprint(order["items"][0]["sku"]) # P1# Safe deep accessemail = order.get("customer", {}).get("email", "n/a")
Common idioms
Counting occurrences
words = "to be or not to be that is the question".split()# Manualcounts = {}for w in words:counts[w] = counts.get(w, 0) + 1# Idiomatic — use Counterfrom collections import Countercounts = Counter(words)print(counts.most_common(3))# [('to', 2), ('be', 2), ('or', 1)]
Grouping items
from collections import defaultdictusers = [{"name": "Aanya", "city": "Noida"},{"name": "Karan", "city": "Bengaluru"},{"name": "Meera", "city": "Noida"}]by_city = defaultdict(list)for u in users:by_city[u["city"]].append(u["name"])print(dict(by_city))# {'Noida': ['Aanya', 'Meera'], 'Bengaluru': ['Karan']}
Key takeaways
- 01Dicts are ordered (since Python 3.7), mutable hash maps with O(1) average lookup.
- 02Use d.get(k, default) for safe reads — never d[k] on data you don't fully trust.
- 03Iterate with .items() to get key and value at the same time.
- 04Dict comprehensions are the cleanest way to transform or filter mappings.
- 05Counter and defaultdict cover 90% of "count" / "group" patterns elegantly.
