- Description:
dict (insertion-ordered hash map since 3.7), set/frozenset, set algebra, and the collections module, defaultdict, Counter, OrderedDict, ChainMap
- My Notion Note ID: K2A-D1-6
- Created: 2022-06-08
- Updated: 2026-05-11
- License: Reuse is very welcome. Please credit Yu Zhang and link back to the original on yuzhang.io
Table of Contents
1. dict
- Hash map, equivalent of C++
std::unordered_map
1.1 Insertion Order Is Guaranteed (3.7+)
- 3.7+: iteration order matches insertion order (language guarantee)
- 3.6: same behavior as CPython implementation detail
- Lookup remains amortized O(1)
d = {"a": 1, "b": 2, "c": 3}
list(d)
1.2 Construction and Lookup
d = {"a": 1, "b": 2}
d = dict(a=1, b=2)
d = dict([("a", 1), ("b", 2)])
d = {k: 0 for k in "abc"}
d["a"]
d["z"]
d.get("z")
d.get("z", 0)
- Use
d.get() when missing-is-normal
- Use
d[k] when missing-is-a-bug
1.3 Useful Methods
d["new"] = 5
del d["a"]
d.pop("a", None)
d.popitem()
d.setdefault("k", [])
d.update(other_dict)
d.clear()
"k" in d
1.4 Views: keys, values, items
for k in d: ...
for k in d.keys(): ...
for v in d.values(): ...
for k, v in d.items(): ...
- Views are live, reflect later mutations of
d
- Set-like:
d.keys() & other.keys() works
1.5 Merging Dicts
merged = a | b
a |= b
merged = {**a, **b}
2. set and frozenset
s = {1, 2, 3}
s = set()
s = set([1, 1, 2])
fs = frozenset([1, 2])
- Set elements must be hashable
frozenset itself is hashable → can be a dict key
2.1 Set Algebra
| Op |
Method |
Meaning |
| |
union |
elements in either |
& |
intersection |
elements in both |
- |
difference |
in left, not in right |
^ |
symmetric_difference |
in exactly one |
<= |
issubset |
every left elt is in right |
>= |
issuperset |
every right elt is in left |
< |
proper subset |
subset and not equal |
a = {1, 2, 3}
b = {2, 3, 4}
a | b
a & b
a - b
a ^ b
a.add(4)
a.discard(99)
a.remove(2)
a.update([5, 6])
3. collections
3.1 defaultdict
- Auto-creates missing values with a zero-arg factory, avoids
setdefault boilerplate
from collections import defaultdict
groups = defaultdict(list)
for name, team in roster:
groups[team].append(name)
freq = defaultdict(int)
for w in words:
freq[w] += 1
3.2 Counter
dict subclass for counting
from collections import Counter
c = Counter("mississippi")
c
c.most_common(2)
c["x"]
c1 + c2
c1 - c2
c1 & c2
c1 | c2
3.3 OrderedDict
- Largely legacy since 3.7
- Still useful for
move_to_end or order-sensitive equality (regular dict compares unordered)
from collections import OrderedDict
od = OrderedDict([("a", 1), ("b", 2)])
od.move_to_end("a")
od.move_to_end("a", last=False)
3.4 ChainMap
- View over multiple mappings, searched in order
- Useful for layered config (CLI > env > defaults)
from collections import ChainMap
config = ChainMap(cli_args, env_vars, defaults)
config["timeout"]
- Writes go to the first map; the underlying maps are not modified