Python 8c – Dictionaries

Store and retrieve values by name using key–value pairs. Create, iterate, update and search dictionaries.

What is a dictionary?

A dictionary stores data as key–value pairs. Keys must be unique; values can be anything (strings, numbers, lists…). Use a key to instantly look up its value.

Creating and displaying a dictionary

Define dictionaries with curly braces {}:

# Define a dictionary of country capitals
capitals = {
    "France": "Paris",
    "Japan": "Tokyo",
    "Brazil": "Brasília",
    "Canada": "Ottawa"
}
print(capitals)
print(*capitals.keys())  # print just the country names

Iterating over a dictionary

Use .items() to get pairs of (key, value):

for country, capital in capitals.items():
    print(country, "→", capital)

Adding and removing entries

Assign to a new key to add; use .pop() to remove safely:

country_capitals = {
    "Italy": "Rome",
    "Spain": "Madrid",
    "Sweden": "Stockholm",
    "Australia": "Canberra"
}

# Add a new entry
country_capitals["Norway"] = "Oslo"
print("After adding Norway:", country_capitals)

# Remove an entry (returns value or default)
removed = country_capitals.pop("Spain", None)
print("Removed capital:", removed)
print("After removal:", country_capitals)

Look up a capital if the country exists:

search_country = input("Enter a country to look up its capital: ")
if search_country in country_capitals:
    print("The capital of", search_country, "is", country_capitals[search_country])
else:
    print("No capital found for", search_country)
Tips:
  • Keys must be unique and hashable (strings, numbers, tuples).
  • Use dict.copy() to duplicate before risky edits.
  • Use dict.get(key, default) to avoid KeyErrors.

Practice tasks

Task 1: Build a country–capital dictionary

Create a dictionary with five countries and their capitals; print it in multiple ways.

Show answer
country_capitals = {
    "Italy": "Rome",
    "Germany": "Berlin",
    "Spain": "Madrid",
    "Sweden": "Stockholm",
    "Australia": "Canberra"
}
print("Full dictionary:", country_capitals)

for c, cap in country_capitals.items():
    print(c, "→", cap)

countries = list(country_capitals.keys())
third = countries[2]  # insertion order preserved in modern Python
print("The capital of", third, "is", country_capitals[third])
Task 2: Modify the dictionary

Add an entry from user input, remove an entry if present, display updated dict.

Show answer
capitals = {
    "Italy": "Rome",
    "Spain": "Madrid",
    "Sweden": "Stockholm",
    "Australia": "Canberra"
}

new_country = input("Enter a new country: ")
new_capital = input("Enter its capital: ")
capitals[new_country] = new_capital

remove_country = input("Enter a country to remove: ")
if remove_country in capitals:
    capitals.pop(remove_country)
else:
    print(remove_country, "is not in the dictionary.")

for k, v in capitals.items():
    print(k, "→", v)
Task 3: Copy and update

Copy your dictionary and change one capital in the copy only.

Show answer
capitals = {
    "France": "Paris",
    "Japan": "Tokyo",
    "Brazil": "Brasília"
}
updated = capitals.copy()

country = input("Country to update: ")
new_capital = input("New capital: ")
if country in updated:
    updated[country] = new_capital
else:
    print(country, "not found.")

print("Original:", capitals)
print("Updated :", updated)
Task 4: Reverse lookup (extension)

Ask for a capital and print the matching country (if any).

Show answer
capitals = {
    "France": "Paris",
    "Japan": "Tokyo",
    "Brazil": "Brasília",
    "Canada": "Ottawa",
}

target = input("Enter a capital: ").strip().lower()
found = False
for country, capital in capitals.items():
    if capital.lower() == target:
        print(capital, "is the capital of", country)
        found = True
        break
if not found:
    print("No country found for that capital.")

Dictionaries in games: Guess the capital

Use a dictionary as the question bank for a mini quiz.

import random

capitals = {
    "France": "Paris",
    "Japan": "Tokyo",
    "Brazil": "Brasília",
    "Canada": "Ottawa",
    "Germany": "Berlin"
}

country = random.choice(list(capitals.keys()))
answer = capitals[country]

print("Guess the capital of", country)
while True:
    guess = input("Your guess: ")
    if guess.lower() == answer.lower():
        print("Well done! The capital of", country, "is", answer)
        break
    else:
        print("Incorrect, try again!")