What is a Dictionary?
A dictionary stores data as key-value pairs. Think of a real dictionary: the word is the key, the definition is the value.
student = {
"name": "Chan Siu Ming",
"age": 17,
"class": "5A",
"subjects": ["Chinese", "English", "Maths", "ICT"]
}
Creating Dictionaries
# Empty dict
d = {}
# With initial values
grades = {"Chan": "A", "Lee": "B", "Wong": "A"}
# Alternative syntax
grades = dict(Chan="A", Lee="B", Wong="A")
Accessing Values
grades = {"Chan": "A", "Lee": "B", "Wong": "A"}
print(grades["Chan"]) # "A"
# Missing key raises KeyError
print(grades["Ho"]) # โ KeyError
# Safe access with .get()
print(grades.get("Ho")) # None
print(grades.get("Ho", "N/A")) # "N/A" (default)
Adding and Updating
grades = {"Chan": "A", "Lee": "B"}
# Add new key
grades["Wong"] = "A"
# {"Chan": "A", "Lee": "B", "Wong": "A"}
# Update existing
grades["Chan"] = "A*"
# {"Chan": "A*", "Lee": "B", "Wong": "A"}
# Update multiple at once
grades.update({"Ho": "C", "Lee": "B*"})
Removing Items
grades = {"Chan": "A", "Lee": "B", "Wong": "A"}
# Delete by key
del grades["Lee"]
# Remove and return value
value = grades.pop("Chan")
print(value) # "A"
# Clear everything
grades.clear()
Checking Membership
grades = {"Chan": "A", "Lee": "B"}
print("Chan" in grades) # True
print("Ho" in grades) # False
print("A" in grades.values()) # True
Iterating Over Dictionaries
grades = {"Chan": "A", "Lee": "B", "Wong": "A"}
# Keys (default)
for name in grades:
print(name)
# Explicitly keys
for name in grades.keys():
print(name)
# Values
for grade in grades.values():
print(grade)
# Both
for name, grade in grades.items():
print(f"{name}: {grade}")
Common Use Case: Counting
text = "hello world"
counts = {}
for char in text:
if char in counts:
counts[char] += 1
else:
counts[char] = 1
# Cleaner with .get()
counts = {}
for char in text:
counts[char] = counts.get(char, 0) + 1
print(counts)
# {'h':1, 'e':1, 'l':3, 'o':2, ' ':1, 'w':1, 'r':1, 'd':1}
Common Use Case: Grouping Data
students = [
("Chan", "A"),
("Lee", "B"),
("Wong", "A"),
("Ho", "C"),
("Lam", "B"),
]
by_grade = {}
for name, grade in students:
if grade not in by_grade:
by_grade[grade] = []
by_grade[grade].append(name)
print(by_grade)
# {'A': ['Chan', 'Wong'], 'B': ['Lee', 'Lam'], 'C': ['Ho']}
Nested Dictionaries
school = {
"5A": {
"Chan": 85,
"Lee": 72,
},
"5B": {
"Wong": 91,
"Ho": 68,
}
}
print(school["5A"]["Chan"]) # 85
# Iterate nested
for class_name, students in school.items():
print(f"Class {class_name}:")
for name, score in students.items():
print(f" {name}: {score}")
Dictionary vs List: When to Use Each
- List: ordered items, access by position (
students[0]) - Dictionary: unordered pairs, access by meaningful key (
grades["Chan"])
Limitations
- Keys must be immutable (strings, numbers, tuples โ NOT lists)
- Keys must be unique (duplicates overwrite)
Build a Dictionary Project
Try building a vocabulary quiz app in PyForm using dictionaries. Best way to learn is to build.
Start Coding โ