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.2.5.1 Create a dictionary
- 11.2.5.2 Search for data in a dictionary for a given key
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 (11.2.5.1)
# 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()Searching & Methods (11.2.5.2)
| 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) |
key in d |
Check if key exists (Search) | "name" in d |
d[key] = value |
Set/update a value | d["age"] = 17 |
d.pop(key) |
Remove key, return value | d.pop("age") |
d.keys() |
All keys | d.keys() |
d.values() |
All values | d.values() |
d.items() |
All key-value pairs as tuples | d.items() |
Searching Effectively
To "search" in a dictionary, checking if key in d: is the most efficient way. It
takes constant time, O(1), regardless of dictionary size.
Worked Examples
1 Word Frequency Counter
text = "the cat sat on the mat the cat"
words = text.split()
freq = {}
for word in words:
# Search if word exists, get current count or 0, then add 1
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]}
# Search for a student
name = input("Enter student name: ")
if name in students:
info = students[name]
avg = sum(info["scores"]) / len(info["scores"])
print(f"{name}: Grade {info['grade']}, Avg Score: {avg:.1f}")
else:
print("Student not found.")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.
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.
Build a student gradebook where users can add students and then search for them to view their GPA.
Self-Check Quiz
d.get("x", 0) do if "x" is not in the
dictionary?