Working with Dictionaries
Objective
Create and manipulate Python dictionaries, use safe access patterns, and leverage specialized dict types.
Tools & Technologies
dictget()items()keys()values()defaultdictCounter
Key Commands
d.get(key, default)d.items()d.update(other)collections.defaultdict(list)Counter(lst).most_common(10)Architecture Overview
graph TD
DICT[dict = key:value pairs]
DICT --> ACCESS[Access\nd[key]\nd.get(key, default)]
DICT --> MUTATE[Mutate\nd[key] = val\ndel d[key]]
DICT --> ITER[Iterate\nd.keys()\nd.values()\nd.items()]
DICT --> MERGE[Merge\nd.update(other)\nd2 = d1 | d2 Python 3.9+]
style DICT fill:#1a1a2e,stroke:#00d4ff,color:#e0e0e0
Step-by-Step Process
01
Create and Access
Build dicts and access values safely.
# Literal syntax
person = {'name': 'Alice', 'age': 25, 'city': 'Toronto'}
# Access
print(person['name']) # KeyError if missing
print(person.get('age')) # None if missing
print(person.get('job', 'N/A')) # default if missing
# Check existence
'name' in person # True
'job' in person # False
02
Iterate and Modify
Loop over dicts and update values.
# Iterate
for key, value in person.items():
print(f'{key}: {value}')
# Modify
person['age'] = 26
person.update({'job': 'developer', 'age': 27})
# Dict comprehension
squares = {n: n**2 for n in range(1, 6)}
# Merge (Python 3.9+)
d3 = d1 | d2
03
Specialized Dict Types
Use defaultdict and Counter for common patterns.
from collections import defaultdict, Counter
# defaultdict: no KeyError for missing keys
wordcount = defaultdict(int)
for word in text.split():
wordcount[word] += 1
# Counter: frequency counting
from collections import Counter
words = ['apple', 'banana', 'apple', 'cherry', 'apple']
c = Counter(words)
print(c.most_common(2)) # [('apple', 3), ('banana', 1)]
Challenges & Solutions
- d['key'] raises KeyError; d.get('key') returns None — always use get() for user-supplied keys
- Dict order is preserved (insertion order) since Python 3.7
Key Takeaways
- Counter is the fastest way to count occurrences of items
- defaultdict eliminates 'if key not in d' boilerplate