1:1 Mentoring with Big Tech AI Engineers
Python
09

Python Collections — Complete Reference

Master these 10 data structures. Know when to reach for each one without thinking.

dict — The Swiss Army Knife

# O(1) avg lookup, insertion, deletion. Ordered since 3.7.
user = {"name": "Alice", "role": "engineer"}
user.get("team", "unknown")           # safe access with default
user.setdefault("team", "platform")   # set if missing, return value
{**user, "level": "senior"}           # merge (Python 3.9+: user | other)

defaultdict — Auto-initializing dict

from collections import defaultdict

# Group items without checking key existence
events_by_type = defaultdict(list)
for event in events:
    events_by_type[event.type].append(event)

# Count with defaultdict(int)
word_count = defaultdict(int)
for word in words:
    word_count[word] += 1

Counter — Frequency counting

from collections import Counter
tools_used = Counter(["search", "search", "calc", "search", "email"])
tools_used.most_common(2)   # [('search', 3), ('calc', 1)]
tools_used["search"]        # 3
tools_used["unknown"]       # 0 (no KeyError!)
tools_used.total()          # 5 (Python 3.10+)

deque — Double-ended queue

Continue Reading

This topic continues with more in-depth content, code examples, and diagrams. Sign up free to unlock the full guide with all 87 sections.

Sign Up Free to Unlock

Free access · No credit card required

More in Python

Get full access to all 87 sections with code examples, diagrams, and interactive animations.

Sign Up Free