Dictionaries
A dictionary stores data as key-value pairs — like a real dictionary where each word (key) has a definition (value). Dictionaries provide fast lookups and are the most versatile data structure in Python.
Learning Objectives
- 11.3.3.1 Use dictionaries for data storage and retrieval
Conceptual Anchor
The Phone Book Analogy
A dictionary is like a phone book: you look up a person's name (key) to find their phone number (value). You don't search through every entry sequentially — you go directly to the name. This is why dictionaries are fast: direct access by key.
Rules & Theory
Creating Dictionaries
# Key: Value pairs in curly braces
student = {
"name": "Ali",
"age": 16,
"grade": "11A",
"gpa": 3.9
}
# Empty dictionary
empty = {}
also_empty = dict()
# dict() constructor
colors = dict(red="#FF0000", green="#00FF00", blue="#0000FF")
# From list of tuples
pairs = [("cat", "мысық"), ("dog", "ит"), ("bird", "құс")]
dictionary = dict(pairs)
print(student["name"]) # "Ali" — access by key
print(student.get("age")) # 16 — access with get()Dictionary Methods
| Method | Description | Example |
|---|---|---|
d[key] |
Get value (KeyError if missing) | d["name"] |
d.get(key, default) |
Get value (default if missing) | d.get("age", 0) |
d[key] = value |
Set/update a value | d["age"] = 17 |
d.pop(key) |
Remove key, return value | d.pop("age") |
del d[key] |
Delete key-value pair | del d["age"] |
d.keys() |
All keys | d.keys() |
d.values() |
All values | d.values() |
d.items() |
All key-value pairs as tuples | d.items() |
key in d |
Check if key exists | "name" in d |
len(d) |
Number of pairs | len(d) |
d.update(d2) |
Merge another dict into d | d.update({"age": 17}) |
Iterating Over Dictionaries
student = {"name": "Ali", "age": 16, "grade": "11A"}
# Iterate over keys (default)
for key in student:
print(key, "=", student[key])
# Iterate over keys explicitly
for key in student.keys():
print(key)
# Iterate over values
for value in student.values():
print(value)
# Iterate over key-value pairs (most useful!)
for key, value in student.items():
print(f"{key}: {value}")
# name: Ali
# age: 16
# grade: 11A.get() vs Direct Access
d["key"] raises KeyError if key doesn't exist.
d.get("key", default) returns the default value instead. Use .get()
when the key might be missing.
Worked Examples
1 Word Frequency Counter
text = "the cat sat on the mat the cat"
words = text.split()
freq = {}
for word in words:
freq[word] = freq.get(word, 0) + 1
# Sort by frequency
for word, count in sorted(freq.items(), key=lambda x: x[1], reverse=True):
print(f"{word}: {count}")
# the: 3
# cat: 2
# sat: 1
# on: 1
# mat: 12 Student Database
students = {}
# Adding students
students["Ali"] = {"age": 16, "grade": "11A", "scores": [85, 90, 78]}
students["Dana"] = {"age": 15, "grade": "11B", "scores": [92, 88, 95]}
students["Marat"] = {"age": 16, "grade": "11A", "scores": [72, 80, 76]}
# Access nested data
print(students["Ali"]["scores"]) # [85, 90, 78]
print(students["Dana"]["age"]) # 15
# Calculate averages
for name, info in students.items():
avg = sum(info["scores"]) / len(info["scores"])
print(f"{name}: avg = {avg:.1f}")3 Menu System
menu = {
"burger": 1500,
"pizza": 2000,
"salad": 1200,
"drink": 500
}
order = []
while True:
item = input("Order (or 'done'): ").lower()
if item == "done":
break
if item in menu:
order.append(item)
print(f"Added {item} — {menu[item]} tenge")
else:
print("Not on menu!")
total = sum(menu[item] for item in order)
print(f"\nTotal: {total} tenge")Pitfalls & Common Errors
KeyError
d["missing_key"] raises KeyError. Always check with
if key in d or use d.get(key, default).
Keys Must Be Immutable
Lists cannot be dictionary keys (they're mutable). Use tuples or strings as keys.
Overwriting Values
d["name"] = "New" overwrites the old value without warning. If a key already exists,
its value is replaced.
Pro-Tips for Exams
Dictionary Tips
freq[word] = freq.get(word, 0) + 1— the standard counting pattern- Use
.items()for the most useful iteration pattern - Dictionaries preserve insertion order (Python 3.7+)
- You can nest dictionaries inside dictionaries for complex data
Graded Tasks
How do you create a dictionary? How do you access a value by its key?
Explain the difference between d["key"] and d.get("key", 0).
Write a program that counts the frequency of each character in a string using a dictionary.
Create a phone book dictionary where users can add, search, and delete contacts.
What is the output of:
d = {"a":1, "b":2}; d["c"] = 3; d["a"] = 10; del d["b"]; print(d)?
Build a student gradebook using nested dictionaries: store multiple students with multiple subjects and scores. Calculate averages.
Self-Check Quiz
d.get("x", 0) do if "x" is not in the
dictionary?