Sets and dicts cheatsheet.
Set basics
s = {1, 2, 3}
s = set([1, 2, 2, 3]) # {1, 2, 3}
empty = set() # not {} (that's a dict!)
s.add(4)
s.remove(4)
s.discard(99) # no error if missing
s.pop() # arbitrary element
1 in s # O(1) membership
len(s)
Set operations
a | b # union
a & b # intersection
a - b # difference
a ^ b # symmetric difference
# In-place
a |= b; a &= b; a -= b; a ^= b
# Subset / superset
a < b # strict subset
a <= b
a > b # strict superset
a.issubset(b)
a.issuperset(b)
a.isdisjoint(b)
Frozenset (immutable, hashable)
fs = frozenset([1, 2, 3])
# Can be a dict key or set element
Set comprehension
unique = {x % 10 for x in numbers}
seen = {p.author_id for p in posts}
Dict basics
d = {"a": 1, "b": 2}
d["a"] # 1
d.get("a", 0)
d.get("missing", "default")
d.setdefault("c", 3) # set if missing; return current
d["d"] = 4
del d["a"]
d.pop("b")
d.pop("missing", None) # safe
"a" in d # O(1)
Iteration
for k in d: ...
for k in d.keys(): ...
for v in d.values(): ...
for k, v in d.items(): ...
Dict merge (3.9+)
a = {"x": 1}
b = {"y": 2}
merged = a | b # {"x": 1, "y": 2}
a |= b # in-place
# Pre-3.9
merged = {**a, **b}
defaultdict
from collections import defaultdict
by_letter = defaultdict(list)
for word in words:
by_letter[word[0]].append(word)
# defaultdict(int) for counters
counts = defaultdict(int)
for x in items:
counts[x] += 1
Counter
from collections import Counter
c = Counter(items)
c.most_common(5)
c.total() # 3.10+
c1 + c2 # combine counts
c1 - c2
c1 & c2 # min
c1 | c2 # max
Dict comprehension
by_id = {u.id: u for u in users}
squared = {x: x**2 for x in range(10)}
filtered = {k: v for k, v in d.items() if v > 0}
inverted = {v: k for k, v in d.items()}
Group by key
from collections import defaultdict
by_author = defaultdict(list)
for post in posts:
by_author[post.author_id].append(post)
Or with itertools (consecutive):
from itertools import groupby
items_sorted = sorted(items, key=lambda x: x.category)
for category, group in groupby(items_sorted, key=lambda x: x.category):
items_in_cat = list(group)
groupby only groups consecutive — sort first if needed.
Sort dict by value
sorted_by_value = dict(sorted(d.items(), key=lambda kv: kv[1]))
top_5 = dict(sorted(d.items(), key=lambda kv: kv[1], reverse=True)[:5])
Pivot / transpose
# List of dicts → dict of lists
records = [{"a": 1, "b": 2}, {"a": 3, "b": 4}]
columns = {k: [r[k] for r in records] for k in records[0]}
# {"a": [1, 3], "b": [2, 4]}
Most common value
from collections import Counter
most = Counter(items).most_common(1)[0] # (value, count)
Set operations on dict keys
a = {"x": 1, "y": 2}
b = {"y": 3, "z": 4}
a.keys() & b.keys() # {"y"}
a.keys() | b.keys() # {"x", "y", "z"}
a.keys() - b.keys() # {"x"}
d.keys() is set-like.
Ordered dicts (insertion order, 3.7+)
d = {"a": 1, "b": 2, "c": 3}
list(d.keys()) # ["a", "b", "c"] — guaranteed
For move-to-end / reorder:
from collections import OrderedDict
od = OrderedDict(d)
od.move_to_end("a") # move to end
od.move_to_end("a", last=False) # move to start
Dict slicing (no built-in; use comprehension)
keys_to_keep = {"a", "b"}
sliced = {k: v for k, v in d.items() if k in keys_to_keep}
TypedDict for shape
from typing import TypedDict
class User(TypedDict):
id: int
name: str
email: str | None
Static typing for dict shapes.
Common mistakes
{}for empty set — that’s a dict. Useset().- Modifying dict during iteration — RuntimeError. Iterate
list(d.items()). - Comparing
dict.keys()to list —dict_keysis set-like, not list. - Using
inon a list when set would be O(1).
Read this next
If you want my dict/set utility recipes, it’s at rajpoot.dev .
Building something AI-, backend-, or data-heavy and want a second pair of eyes? I do consulting and freelance work — see my projects and ways to reach me at rajpoot.dev .