Skip to main content
Albero Academy

Python Dictionaries

Master Python dictionaries — creation, access patterns, CRUD operations, iteration, comprehensions, nested dicts, and common idioms.

Chapter 7Python18 min readBeginner friendly
  • #Python
  • #Dictionaries
  • #Key-Value

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

Python
# Literal — most common
user = {"name": "Aanya", "age": 28, "city": "Noida"}
# Empty dict
empty = {}
empty2 = dict()
# From keyword arguments
user2 = dict(name="Karan", age=32, city="Bengaluru")
# From a list of pairs
user3 = 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

Python
user = {"name": "Aanya", "age": 28}
# Bracket access — raises KeyError if missing
print(user["name"]) # Aanya
# .get() — returns None if missing, no error
print(user.get("city")) # None
print(user.get("city", "Noida")) # Noida — default value
# Membership check
print("age" in user) # True
print("salary" in user) # False

Add · update · delete

Python
user = {"name": "Aanya", "age": 28}
# Add or update — same syntax
user["city"] = "Noida" # add
user["age"] = 29 # update
user.update({"role": "Analyst", "salary_lpa": 12.4})
# Delete
del user["salary_lpa"]
removed = user.pop("role") # also returns the value
last = user.popitem() # removes & returns last inserted (key, value)
user.clear() # empties the dict

Useful methods

MethodReturns
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
Python
a = {"x": 1, "y": 2}
b = {"y": 99, "z": 3}
# Merge with | (Python 3.9+) — values in b win on collision
merged = a | b
print(merged) # {'x': 1, 'y': 99, 'z': 3}
# In-place merge with |=
a |= b
print(a) # {'x': 1, 'y': 99, 'z': 3}

Iterating over a dict

Python
scores = {"Aanya": 92, "Karan": 87, "Meera": 95}
# Default — iterates over keys
for name in scores:
print(name)
# Values only
for score in scores.values():
print(score)
# Most useful: items() — both at once
for name, score in scores.items():
print(f"{name}: {score}")

Dict comprehensions

Python
# Squares of 0-4 keyed by the number
squares = {n: n * n for n in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
# Filter — keep passing scores only
scores = {"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 keys
codes = {"in": 91, "us": 1, "uk": 44}
flipped = {v: k for k, v in codes.items()}
# {91: 'in', 1: 'us', 44: 'uk'}

Nested dictionaries

Python
# A common shape — JSON-like data
order = {
"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"]) # Aanya
print(order["items"][0]["sku"]) # P1
# Safe deep access
email = order.get("customer", {}).get("email", "n/a")

Common idioms

Counting occurrences

Python
words = "to be or not to be that is the question".split()
# Manual
counts = {}
for w in words:
counts[w] = counts.get(w, 0) + 1
# Idiomatic — use Counter
from collections import Counter
counts = Counter(words)
print(counts.most_common(3))
# [('to', 2), ('be', 2), ('or', 1)]

Grouping items

Python
from collections import defaultdict
users = [
{"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

  1. 01Dicts are ordered (since Python 3.7), mutable hash maps with O(1) average lookup.
  2. 02Use d.get(k, default) for safe reads — never d[k] on data you don't fully trust.
  3. 03Iterate with .items() to get key and value at the same time.
  4. 04Dict comprehensions are the cleanest way to transform or filter mappings.
  5. 05Counter and defaultdict cover 90% of "count" / "group" patterns elegantly.