Python Dictionaries
Learn to use dictionaries for key-value pairs, common methods, iteration techniques, and nested dictionaries.
Creating and Accessing Dictionaries
A dictionary stores data as key-value pairs inside curly braces {}. Each key maps to a value, like a real dictionary maps words to definitions. Keys must be unique and immutable (strings, numbers).
# Creating a dictionary
student = {
"name": "Alice",
"age": 16,
"year": 11,
"subjects": ["Maths", "English", "Science"]
}
# Accessing values
print(student["name"]) # Alice
print(student["age"]) # 16
print(student.get("email", "Not provided")) # Safe access with default
# Adding and updating
student["email"] = "[email protected]" # Add new key
student["age"] = 17 # Update existing key
print(student)
.get(key, default) to avoid errors when a key might not exist.
Dictionary Methods and Iteration
Dictionaries have powerful built-in methods for working with keys, values, and items. You can loop through dictionaries in several ways.
scores = {"Maths": 85, "English": 92, "Science": 78}
# Useful methods
print(scores.keys()) # dict_keys(['Maths', 'English', 'Science'])
print(scores.values()) # dict_values([85, 92, 78])
print(scores.items()) # dict_items([('Maths', 85), ...])
# Iteration
for subject in scores:
print(f"{subject}: {scores[subject]}")
# Better: iterate over key-value pairs
for subject, mark in scores.items():
print(f"{subject}: {mark}%")
# Removing items
removed = scores.pop("Science") # Removes and returns value
print(f"Removed Science: {removed}")
print(f"Remaining: {scores}")
Nested Dictionaries
Dictionaries can contain other dictionaries as values. This creates nested structures useful for organising complex data like student records or contact databases.
# Nested dictionary: class of students
classroom = {
"Alice": {"age": 16, "grade": "A", "score": 92},
"Bob": {"age": 17, "grade": "B", "score": 81},
"Charlie": {"age": 16, "grade": "A", "score": 95}
}
# Accessing nested values
print(classroom["Alice"]["score"]) # 92
print(classroom["Bob"]["grade"]) # B
# Loop through all students
for name, info in classroom.items():
print(f"{name} (age {info['age']}): {info['grade']} - {info['score']}%")
Key Vocabulary
Dictionary
A collection of key-value pairs enclosed in curly braces {}.
Key
A unique identifier used to look up a value, like "name" in a student record.
Value
The data associated with a key. Can be any data type including lists or other dictionaries.
Nested Dictionary
A dictionary that contains another dictionary as one of its values.
Worked Examples
Count letter frequency in a word
word = "mississippi"
frequency = {}
for letter in word:
if letter in frequency:
frequency[letter] += 1
else:
frequency[letter] = 1
for letter, count in frequency.items():
print(f"'{letter}': {count}")
Step 1: We start with an empty dictionary and loop through each letter.
Step 2: If the letter exists as a key, increment its count. Otherwise, set it to 1.
Create a phone book with add and search
phone_book = {}
# Adding contacts
phone_book["Alice"] = "0412 345 678"
phone_book["Bob"] = "0423 456 789"
phone_book["Charlie"] = "0434 567 890"
# Searching
search_name = "Bob"
if search_name in phone_book:
print(f"{search_name}: {phone_book[search_name]}")
else:
print(f"{search_name} not found")
# List all contacts
print(f"\nAll contacts ({len(phone_book)}):")
for name, number in sorted(phone_book.items()):
print(f" {name}: {number}")
Step 1: We use names as keys and phone numbers as values.
Step 2: Use in to check if a key exists before accessing it.
Calculate class averages from a nested dictionary
students = {
"Alice": {"maths": 85, "english": 92, "science": 88},
"Bob": {"maths": 76, "english": 81, "science": 79},
"Charlie": {"maths": 95, "english": 89, "science": 91}
}
for name, subjects in students.items():
scores = subjects.values()
avg = sum(scores) / len(scores)
print(f"{name}: average = {avg:.1f}%")
Step 1: Each student has a nested dictionary of subject scores.
Step 2: .values() gives us all scores, which we can sum and average.
Knowledge Check
Select the correct answer for each question. Click "Check Answer" to see if you are right.
Question 1
What does {"a": 1, "b": 2}["b"] return?
Question 2
Which method returns all keys from a dictionary?
Question 3
What happens if you access a key that does not exist using dict["missing_key"]?
Question 4
How do you add a new key-value pair "colour": "blue" to an existing dictionary d?
Question 5
Which method iterates over both keys AND values together?
Key Concepts Summary
-
●
Dictionaries store key-value pairs in curly braces
{key: value}. -
●
Access values with
dict[key]or safely withdict.get(key, default). -
●
Key methods:
.keys(),.values(),.items(),.pop(). -
●
Use
for key, value in dict.items():to iterate over pairs. - ● Dictionaries can be nested to represent complex structured data.