Dictionaries & Sets
Overview
Dictionaries store key-value pairs, and sets store unique values. Both provide fast lookups.
Learning Objectives
- Create dictionaries to map keys to values.
- Deduplicate collections using sets.
- Use get() to prevent KeyError errors.
Concept Explanation
Dictionaries and sets use hash tables. Keys must be hashable (immutable values like strings, numbers, or tuples). Lookups, additions, and deletions are extremely fast, running in O(1) average time.
Code Examples
Example 1 — Basics
This example introduces the fundamental syntax and concepts.
user = {'name': 'Alice', 'role': 'admin'}
unique_ids = {101, 102, 103}
Example 2 — Everyday Usage
This example demonstrates a realistic scenario handling business parameters.
user_status = {'alex': 'active', 'bob': 'offline'}
# Safe key lookup using get()
status = user_status.get('charlie', 'unknown')
print(f'Charlie status: {status}')
Example 3 — Advanced Example
This example shows clean, production-grade code structure following senior development standards.
# Deduplicate log IDs list using sets
def get_unique_logs(log_ids):
seen = set()
for log_id in log_ids:
seen.add(log_id) # O(1) average addition
return seen
print(get_unique_logs([201, 202, 201, 203, 202]))
Visual Flow
The following execution flow represents the step-by-step evaluation inside the interpreter:
Evaluate Key → Calculate hash value → Map to bucket index → Retrieve matching value reference
Common Mistakes
Review these common pitfalls when working with this topic:
- Using mutable keys (like lists) in dictionaries, which raises a TypeError.
- Accessing missing keys directly using dict[key] instead of using dict.get(key).
- Modifying dictionary keys or set sizes during loop runs.
- Creating an empty set using s = (this actually creates an empty dictionary; use s = set() instead).
Best Practices
Enforce these Pythonic best practices in your codebase:
s = {}
s.add(1) # Raises AttributeError on dict
s = set()
s.add(1) # Correct set declaration
Performance Notes
Keep these optimization guidelines in mind for performance-sensitive hotpaths:
- Dictionary and set lookups run in O(1) average time, making them significantly faster than searching lists (which takes O(N) time).
Quick Revision
Use these key summaries for last-minute revision:
- Dictionaries associate unique keys with values.
- Sets store unique, unordered elements.
- Both use hash tables for O(1) average lookups.
- Keys must be immutable (hashable).
- Use dict.get() to avoid KeyError crashes.
- Use set() to initialize empty sets.