Programmer's Picnic · Python Foundations · 0 → ∞
Python Dictionaries: From 0 to Infinity
Organise data under meaningful names and build small record-processing programs.
How to learn
Read one level, type the code into the editor, predict the output, then run it. Change one line and observe the result before proceeding. All code examples work with standard Python 3 (the dictionary union example requires 3.9 or newer).
The course moves from first principles to realistic code, common mistakes, performance and a mini-project.
0 · Keys and values
A dictionary maps unique hashable keys to values. It is mutable and maintains insertion order in modern Python (3.7+).
student = {'name': 'Asha', 'marks': 89}
print(student['name'])
print(len(student))
print(type(student).__name__)Asha
2
dictRemember: A key occurs only once. Writing it again replaces the prior value.
1 · Safe lookups
Accessing a missing key with [] raises KeyError. get() returns None or a supplied default when the key is absent.
record = {'name': 'Ravi'}
print(record.get('marks'))
print(record.get('marks', 0))
print('name' in record)None
0
TrueRemember: Choose [] when absence is a programming error; use get() for optional fields.
2 · Insert, update and delete
Assigning to a key inserts or replaces a value. update() changes several fields. pop() removes and returns a value.
stock = {'pen': 10}
stock['pen'] += 5
stock['book'] = 4
stock.update({'eraser': 8})
removed = stock.pop('book')
print(stock)
print(removed){'pen': 15, 'eraser': 8}
4Remember: pop('missing', default) avoids KeyError; clear() empties the dictionary.
3 · Iterate over items
A loop over a dict yields keys. items() yields key-value pairs; values() yields values. Keep the order predictable by sorting if needed.
marks = {'Asha': 80, 'Ravi': 75}
for name, score in marks.items():
print(f'{name}: {score}')
print(sum(marks.values()))Asha: 80
Ravi: 75
155Remember: Do not add or delete keys while iterating over the same dictionary.
4 · Nested dictionaries
Store meaningful records as dictionaries inside a larger dictionary. get() can help with missing optional fields.
students = {
'S01': {'name': 'Asha', 'marks': 90},
'S02': {'name': 'Ravi', 'marks': 73}
}
print(students['S02']['name'])
print(students['S01']['marks'])Ravi
90Remember: For more structured applications, consider dataclasses, database tables or typed models.
5 · Dictionary comprehensions
Transform an iterable into a key-value mapping, optionally filtering or converting values.
marks = {'Asha': 90, 'Ravi': 38, 'Meera': 75}
passed = {name: score for name, score in marks.items() if score >= 40}
print(passed){'Asha': 90, 'Meera': 75}Remember: If generated keys repeat, later values overwrite earlier ones.
6 · Count occurrences
Counter is a dictionary-like class designed for frequencies. Use it instead of manual counting when possible.
from collections import Counter
items = ['pen', 'book', 'pen', 'eraser', 'pen']
counts = Counter(items)
print(counts['pen'])
print(counts.most_common(2))3
[('pen', 3), ('book', 1)]Remember: Counter returns 0 for missing keys when accessed with [] instead of KeyError.
7 · setdefault and defaultdict
Use setdefault() to create a missing key with a default. defaultdict(list) is convenient for grouping many records.
from collections import defaultdict
by_city = defaultdict(list)
for name, city in [('Asha', 'Varanasi'), ('Ravi', 'Ranchi'), ('Meera', 'Varanasi')]:
by_city[city].append(name)
print(by_city['Varanasi'])['Asha', 'Meera']Remember: Accessing a missing defaultdict key creates a value; this side effect may be surprising.
8 · Combine dictionaries and views
Use {**a, **b} in older Python or a | b in Python 3.9+ to make a new dictionary. Later values win for duplicate keys.
a = {'pen': 10, 'book': 5}
b = {'book': 8, 'eraser': 2}
c = a | b
print(c)
print(list(c.keys())){'pen': 10, 'book': 8, 'eraser': 2}
['pen', 'book', 'eraser']Remember: a |= b updates a itself. keys(), values() and items() are dynamic view objects.
9 · Valid keys and performance
Dictionary keys must be hashable, so strings, numbers and suitable tuples work. Lists cannot be keys. Typical lookup and insertion are O(1) average.
prices = {('Varanasi', 'pen'): 12}
print(prices.get(('Varanasi', 'pen')))
print(('Patna', 'pen') in prices)12
FalseRemember: A dictionary preserves insertion order, but that does not mean its keys are alphabetically sorted.
10 · Mini-project: inventory report
Maintain stock and display reorder items using clear business rules. Turn the print loop into a function for reuse.
stock = {'rice': 12, 'dal': 4, 'oil': 2}
reorder_level = 5
for item, qty in stock.items():
status = 'REORDER' if qty < reorder_level else 'OK'
print(f'{item}: {qty} — {status}')rice: 12 — OK
dal: 4 — REORDER
oil: 2 — REORDERRemember: Extension: process a delivery by increasing stock only when its quantity is nonnegative.
Test your understanding
Predict or explain the answer before opening the solution. Try rewriting one of the examples without copying it.
1. What happens when data['missing'] is used?
Answer: KeyError
Try data.get('missing', default) for optional keys.
2. What happens when a dict comprehension produces duplicate keys?
Answer: Later values replace earlier values.
Keys are unique.
3. What does a | b do for dictionaries in Python 3.9+?
Answer: Creates a merged dictionary, preferring b on duplicate keys.
a and b remain unchanged.
Take it further: expand the mini-project with an input() prompt, a reusable function, input validation and three tests (normal, empty and boundary cases).
When to use each Python collection
| Type | Ordered? | Mutable? | Duplicates? | Best for |
|---|---|---|---|---|
| str | Yes | No | Yes | Text |
| list | Yes | Yes | Yes | Changing sequences |
| tuple | Yes | No* | Yes | Fixed records |
| set | No guaranteed order | Yes | No | Unique membership |
| dict | Insertion order | Yes | Keys unique | Named lookups |
* A tuple itself cannot be reassigned, but a mutable item stored inside it can still change.
Programmer's Picnic · Developed and maintained by Champak Roy · Practice with real Python, one step at a time.