BrightPath
Back to Course
Year 10 Coding

Python Dictionaries

Learn to store and retrieve data using key-value pairs, dictionary methods, and iteration techniques.

What Are Dictionaries?

A dictionary stores data as key-value pairs. Think of it like a real dictionary: you look up a word (the key) to find its definition (the value). In Python, dictionaries are defined with curly braces {}.

# Creating a dictionary
student = {
    "name": "Ava",
    "age": 15,
    "year": 10,
    "school": "BrightPath Academy"
}

# Accessing values by key
print(student["name"])      # Output: Ava
print(student["year"])      # Output: 10

# Using .get() -- safer, returns None if key doesn't exist
print(student.get("email"))          # Output: None
print(student.get("email", "N/A"))   # Output: N/A (default value)

Unlike lists (which use numeric indices), dictionaries use meaningful keys to access values. Keys must be unique and immutable (strings and numbers are common choices). Values can be any data type.

Common Dictionary Methods

Python dictionaries come with powerful built-in methods for adding, removing, and inspecting data:

scores = {"maths": 85, "english": 92, "science": 78}

# Adding or updating a key-value pair
scores["art"] = 90              # Add new key
scores["maths"] = 88            # Update existing key

# Removing entries
scores.pop("science")           # Removes "science" and returns 78

# Useful methods
print(scores.keys())            # dict_keys(['maths', 'english', 'art'])
print(scores.values())          # dict_values([88, 92, 90])
print(scores.items())           # dict_items([('maths', 88), ('english', 92), ('art', 90)])
print(len(scores))              # 3  (number of key-value pairs)
print("english" in scores)      # True  (check if key exists)

Use .keys() to get all keys, .values() for all values, and .items() for key-value pairs as tuples.

Iterating Over Dictionaries

You can loop through dictionaries using for loops. By default, looping over a dictionary iterates over its keys. Use .items() to get both keys and values simultaneously.

scores = {"maths": 88, "english": 92, "art": 90}

# Loop through keys only
for subject in scores:
    print(subject)
# Output: maths, english, art

# Loop through keys and values together
for subject, mark in scores.items():
    print(f"{subject}: {mark}%")
# Output: maths: 88%, english: 92%, art: 90%

# Calculate average from dictionary values
total = sum(scores.values())
average = total / len(scores)
print(f"Average: {average:.1f}%")   # Output: Average: 90.0%

Dictionaries are ideal for storing structured data like student records, configuration settings, or any data where you need fast lookup by a meaningful label.

Key Vocabulary

Dictionary

A Python data structure that stores key-value pairs in curly braces, allowing fast data lookup by key.

Key

The unique identifier used to look up a value in a dictionary. Keys must be immutable (e.g. strings, numbers).

Value

The data associated with a key. Values can be any data type: strings, numbers, lists, or even other dictionaries.

Key-Value Pair

A single entry in a dictionary consisting of a key and its associated value, written as key: value.

Worked Examples

1

Create a dictionary of Australian state capitals and look up a value.

capitals = {
    "NSW": "Sydney",
    "VIC": "Melbourne",
    "QLD": "Brisbane",
    "WA": "Perth",
    "SA": "Adelaide"
}

state = "QLD"
print(f"The capital of {state} is {capitals[state]}.")
# Output: The capital of QLD is Brisbane.

Step 1: Define the dictionary with state abbreviations as keys and city names as values.

Step 2: Access the value using the key in square brackets.

Result: Fast, readable lookup of structured data.

2

Count the frequency of each letter in a word using a dictionary.

word = "banana"
freq = {}

for letter in word:
    if letter in freq:
        freq[letter] += 1
    else:
        freq[letter] = 1

print(freq)   # Output: {'b': 1, 'a': 3, 'n': 2}

Step 1: Start with an empty dictionary.

Step 2: Loop through each letter. If it is already a key, increment its count; otherwise, add it with a count of 1.

Result: A frequency map showing how many times each letter appears.

3

Find the student with the highest score from a dictionary.

results = {"Ava": 92, "Ben": 85, "Chloe": 97, "Dan": 88}

top_student = max(results, key=results.get)
print(f"Top student: {top_student} with {results[top_student]}%")
# Output: Top student: Chloe with 97%

Step 1: Use max() on the dictionary with key=results.get to compare by values.

Step 2: This returns the key (student name) associated with the highest value (score).

Result: Chloe has the highest score at 97%.

Knowledge Check

Select the correct answer for each question. Click "Check Answer" to see if you are right.

Question 1

Which brackets are used to define a dictionary in Python?

Question 2

Given d = {"a": 1, "b": 2, "c": 3}, what does d["b"] return?

Question 3

Which method returns all the keys in a dictionary?

Question 4

What does d.get("z", 0) return if "z" is not a key in dictionary d?

Question 5

When you loop over a dictionary with for x in my_dict:, what does x represent?

Key Concepts Summary

Year 10: String Methods Year 10: File Handling