Programmer's Picnic · Python Foundations · 0 → ∞

Python Dictionaries: From 0 to Infinity

Organise data under meaningful names and build small record-processing programs.

Free course · 65–90 minutes reading and practice · No installation beyond Python 3

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.

Level 0 / 10

0 · Keys and values

A dictionary maps unique hashable keys to values. It is mutable and maintains insertion order in modern Python (3.7+).

Python 3 · runnable example
student = {'name': 'Asha', 'marks': 89}
print(student['name'])
print(len(student))
print(type(student).__name__)
Expected output
Asha
2
dict

Remember: A key occurs only once. Writing it again replaces the prior value.

Level 1 / 10

1 · Safe lookups

Accessing a missing key with [] raises KeyError. get() returns None or a supplied default when the key is absent.

Python 3 · runnable example
record = {'name': 'Ravi'}
print(record.get('marks'))
print(record.get('marks', 0))
print('name' in record)
Expected output
None
0
True

Remember: Choose [] when absence is a programming error; use get() for optional fields.

Level 2 / 10

2 · Insert, update and delete

Assigning to a key inserts or replaces a value. update() changes several fields. pop() removes and returns a value.

Python 3 · runnable example
stock = {'pen': 10}
stock['pen'] += 5
stock['book'] = 4
stock.update({'eraser': 8})
removed = stock.pop('book')
print(stock)
print(removed)
Expected output
{'pen': 15, 'eraser': 8}
4

Remember: pop('missing', default) avoids KeyError; clear() empties the dictionary.

Level 3 / 10

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.

Python 3 · runnable example
marks = {'Asha': 80, 'Ravi': 75}
for name, score in marks.items():
    print(f'{name}: {score}')
print(sum(marks.values()))
Expected output
Asha: 80
Ravi: 75
155

Remember: Do not add or delete keys while iterating over the same dictionary.

Level 4 / 10

4 · Nested dictionaries

Store meaningful records as dictionaries inside a larger dictionary. get() can help with missing optional fields.

Python 3 · runnable example
students = {
    'S01': {'name': 'Asha', 'marks': 90},
    'S02': {'name': 'Ravi', 'marks': 73}
}
print(students['S02']['name'])
print(students['S01']['marks'])
Expected output
Ravi
90

Remember: For more structured applications, consider dataclasses, database tables or typed models.

Level 5 / 10

5 · Dictionary comprehensions

Transform an iterable into a key-value mapping, optionally filtering or converting values.

Python 3 · runnable example
marks = {'Asha': 90, 'Ravi': 38, 'Meera': 75}
passed = {name: score for name, score in marks.items() if score >= 40}
print(passed)
Expected output
{'Asha': 90, 'Meera': 75}

Remember: If generated keys repeat, later values overwrite earlier ones.

Level 6 / 10

6 · Count occurrences

Counter is a dictionary-like class designed for frequencies. Use it instead of manual counting when possible.

Python 3 · runnable example
from collections import Counter
items = ['pen', 'book', 'pen', 'eraser', 'pen']
counts = Counter(items)
print(counts['pen'])
print(counts.most_common(2))
Expected output
3
[('pen', 3), ('book', 1)]

Remember: Counter returns 0 for missing keys when accessed with [] instead of KeyError.

Level 7 / 10

7 · setdefault and defaultdict

Use setdefault() to create a missing key with a default. defaultdict(list) is convenient for grouping many records.

Python 3 · runnable example
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'])
Expected output
['Asha', 'Meera']

Remember: Accessing a missing defaultdict key creates a value; this side effect may be surprising.

Level 8 / 10

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.

Python 3 · runnable example
a = {'pen': 10, 'book': 5}
b = {'book': 8, 'eraser': 2}
c = a | b
print(c)
print(list(c.keys()))
Expected output
{'pen': 10, 'book': 8, 'eraser': 2}
['pen', 'book', 'eraser']

Remember: a |= b updates a itself. keys(), values() and items() are dynamic view objects.

Level 9 / 10

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.

Python 3 · runnable example
prices = {('Varanasi', 'pen'): 12}
print(prices.get(('Varanasi', 'pen')))
print(('Patna', 'pen') in prices)
Expected output
12
False

Remember: A dictionary preserves insertion order, but that does not mean its keys are alphabetically sorted.

Level 10 / 10

10 · Mini-project: inventory report

Maintain stock and display reorder items using clear business rules. Turn the print loop into a function for reuse.

Python 3 · runnable example
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}')
Expected output
rice: 12 — OK
dal: 4 — REORDER
oil: 2 — REORDER

Remember: Extension: process a delivery by increasing stock only when its quantity is nonnegative.

Practice lab

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

Comparison of Python built-in data types
TypeOrdered?Mutable?Duplicates?Best for
strYesNoYesText
listYesYesYesChanging sequences
tupleYesNo*YesFixed records
setNo guaranteed orderYesNoUnique membership
dictInsertion orderYesKeys uniqueNamed lookups

* A tuple itself cannot be reassigned, but a mutable item stored inside it can still change.

Python official built-in types reference ↗

Programmer's Picnic · Developed and maintained by Champak Roy · Practice with real Python, one step at a time.