Dictionaries

Data Structures: Dictionaries

A dictionary stores data in key-value pairs. Each key identifies a value.

Dictionaries are useful for structured records, such as a person’s profile, a product catalogue, or the settings of an application.

Creating Dictionaries

Create a dictionary with curly brackets {}. Separate each key from its value with a colon.

person = {
    "name": "John",
    "age": 25,
    "city": "New York",
}

print(person)
{'name': 'John', 'age': 25, 'city': 'New York'}
print(type(person))
<class 'dict'>

Use empty curly brackets to create an empty dictionary.

empty_dictionary = {}

print(empty_dictionary)
{}
print(type(empty_dictionary))
<class 'dict'>

Remember that an empty set uses set() instead.

empty_set = set()

print(type(empty_set))
<class 'set'>

Keys and Values

Keys must be unique and immutable. Strings, numbers, and tuples can be keys. Values can have any data type and may be duplicated.

course = {
    "title": "Introduction to Python",
    "students": 32,
    "online": True,
    "topics": ["variables", "loops", "functions"],
    "room": (4, 12),
}

print(course)
{'title': 'Introduction to Python', 'students': 32, 'online': True, 'topics': ['variables', 'loops', 'functions'], 'room': (4, 12)}

You can also use variables when defining keys or values.

student_name = "Maya"
grade_key = "grade"

student = {
    "name": student_name,
    grade_key: 8.7,
    "programme": "Data Science",
}

print(student)
{'name': 'Maya', 'grade': 8.7, 'programme': 'Data Science'}
Warning

Lists and sets cannot be dictionary keys because they are mutable. Tuples can be keys if all their items are immutable.

classrooms = {
    ("Monday", "09:00"): "Room A",
    ("Tuesday", "11:00"): "Room C",
}

print(classrooms)
{('Monday', '09:00'): 'Room A', ('Tuesday', '11:00'): 'Room C'}

Accessing Values

Access a value by writing its key inside square brackets.

person = {
    "name": "John",
    "age": 25,
    "city": "New York",
}

print(person["name"])
John
print(person["age"])
25

Insertion Order and Position

Modern Python dictionaries preserve insertion order. However, they are accessed by key, not by position.

print(person[0])
KeyError: 0

The code fails because 0 is not a key in person.

Numeric keys are valid, but Python still treats them as keys rather than positions.

numbers = {
    3: "three",
    4: "four",
    5: "five",
}

print(numbers[3])
three
print(numbers[0])
KeyError: 0

Accessing Values Safely

Square brackets raise a KeyError when the requested key does not exist.

print(person["email"])
KeyError: 'email'

The get() method returns None instead of raising an error.

print(person.get("email"))
None

You can provide a default value as the second argument.

print(person.get("email", "Email not available"))
Email not available
Exercise: Read a record

Use the dictionary below to print the book’s title and publication year in separate cells.

book = {
    "title": "Kindred",
    "author": "Octavia Butler",
    "year": 1979,
}
print(book["title"])
print(book["year"])

Mutable

Dictionaries are mutable. You can add, update, and remove key-value pairs.

Updating a Value

Assign a new value to an existing key.

person = {
    "name": "John",
    "age": 25,
    "city": "New York",
}

print(person)
{'name': 'John', 'age': 25, 'city': 'New York'}
person["age"] = 26

print(person)
{'name': 'John', 'age': 26, 'city': 'New York'}

Adding a Pair

Assigning a value to a new key adds a new key-value pair.

person["email"] = "john@example.com"

print(person)
{'name': 'John', 'age': 26, 'city': 'New York', 'email': 'john@example.com'}

Removing a Pair

Use del to remove a key and its value.

del person["city"]

print(person)
{'name': 'John', 'age': 26, 'email': 'john@example.com'}

The pop() method removes a key and returns its value.

removed_email = person.pop("email")

print(removed_email)
john@example.com
print(person)
{'name': 'John', 'age': 26}
Exercise: Update an event

Make these changes to the dictionary:

  1. Change the venue to "Main Hall".
  2. Add the pair "sold_out": False.
  3. Remove the "dress_code" pair.
event = {
    "name": "Data Night",
    "venue": "Room 2",
    "dress_code": "Casual",
}
event["venue"] = "Main Hall"
event["sold_out"] = False
del event["dress_code"]

print(event)

Unique Keys

A dictionary cannot contain duplicate keys. If the same key appears more than once, the last value replaces the earlier value.

person = {
    "name": "John",
    "name": "Smith",
    "age": 25,
}

print(person)
{'name': 'Smith', 'age': 25}

Different keys may contain the same value.

locations = {
    "home_city": "Madrid",
    "work_city": "Madrid",
}

print(locations)
{'home_city': 'Madrid', 'work_city': 'Madrid'}

Membership

The in operator checks dictionary keys, not values.

person = {
    "name": "John",
    "age": 25,
    "city": "New York",
}

print("name" in person)
True
print("John" in person)
False

Use .values() if you need to search among the values.

print("John" in person.values())
True
Exercise: Predict the output

Without running the code, determine the result of each expression.

settings = {
    "theme": "dark",
    "language": "English",
    "notifications": True,
}
print("theme" in settings)
print("dark" in settings)
print("dark" in settings.values())

The three results are True, False, and True.

Dictionary Methods

Three useful methods provide views of a dictionary:

  • keys() returns the keys.
  • values() returns the values.
  • items() returns key-value pairs as tuples.
product = {
    "name": "Headphones",
    "price": 79.99,
    "stock": 14,
}

print(product.keys())
dict_keys(['name', 'price', 'stock'])
print(product.values())
dict_values(['Headphones', 79.99, 14])
print(product.items())
dict_items([('name', 'Headphones'), ('price', 79.99), ('stock', 14)])

The update() method adds new pairs and replaces values for existing keys.

product.update({"price": 69.99, "colour": "black"})

print(product)
{'name': 'Headphones', 'price': 69.99, 'stock': 14, 'colour': 'black'}

Looping Through a Dictionary

A for loop over a dictionary visits its keys.

for key in product:
    print(key)
name
price
stock
colour

Use .items() when you need both the key and the value.

for key, value in product.items():
    print(f"{key}: {value}")
name: Headphones
price: 69.99
stock: 14
colour: black

Each loop contains one print() statement, even though it produces several output lines.

Exercise: Display a profile

Use a loop and .items() to print each key and value in this format:

username: maya_21
level: 8
premium: True
profile = {
    "username": "maya_21",
    "level": 8,
    "premium": True,
}
for key, value in profile.items():
    print(f"{key}: {value}")

Nested Dictionaries

A dictionary can contain other dictionaries. This is useful when several records share the same structure.

students = {
    "S001": {
        "name": "Maya",
        "programme": "Data Science",
        "grade": 8.7,
    },
    "S002": {
        "name": "Leo",
        "programme": "Economics",
        "grade": 7.9,
    },
}

print(students)
{'S001': {'name': 'Maya', 'programme': 'Data Science', 'grade': 8.7}, 'S002': {'name': 'Leo', 'programme': 'Economics', 'grade': 7.9}}

Use one key for the outer dictionary and another for the nested dictionary.

print(students["S001"]["name"])
Maya
print(students["S002"]["grade"])
7.9
Exercise: Update a nested record

Using the students dictionary above:

  1. Change Maya’s grade to 9.1.
  2. Add a new field, "graduated": False, to Leo’s record.
  3. Print each updated student record in a separate cell.
students["S001"]["grade"] = 9.1
students["S002"]["graduated"] = False
print(students["S001"])
print(students["S002"])

Converting to a Dictionary

The dict() function can convert a sequence of key-value pairs into a dictionary.

pairs = [
    ("name", "Pipo"),
    ("age", 10),
    ("city", "Seville"),
]

converted_dictionary = dict(pairs)

print(converted_dictionary)
{'name': 'Pipo', 'age': 10, 'city': 'Seville'}
Exercise: Convert a menu

Convert the following list of tuples into a dictionary. Then print the price of the salad.

menu_pairs = [
    ("soup", 6.50),
    ("salad", 8.00),
    ("pasta", 12.50),
]
menu = dict(menu_pairs)
print(menu["salad"])

Challenge: Count Words

Create a dictionary that counts how many times each word appears in the list.

words = ["python", "data", "python", "model", "data", "python"]

The expected dictionary is:

{"python": 3, "data": 2, "model": 1}
word_counts = {}

for word in words:
    word_counts[word] = word_counts.get(word, 0) + 1
print(word_counts)

Lists, Tuples, Sets, and Dictionaries Compared

Data structure Syntax Preserves order Mutable Duplicate items Access
List [] Yes Yes Yes Position
Tuple () Yes No Yes Position
Set {item, ...} or set() No Yes No Membership
Dictionary {key: value} Yes Yes Keys: No; values: Yes Key

Use a list when position matters and the collection may change. Use a tuple when position matters and the collection should remain fixed. Use a set for unique items and membership tests. Use a dictionary when each value needs a meaningful identifier.

Summary

  • Dictionaries store key-value pairs.
  • Keys must be unique and immutable.
  • Values can use any data type and may be duplicated.
  • Dictionaries preserve insertion order but use keys for access.
  • Dictionaries are mutable.
  • get() provides safe access to a missing key.
  • keys(), values(), and items() provide different views of the data.
  • Nested dictionaries store structured collections of records.

Homework and Review

Work through the “Dictionaries” homework exercises available here. To earn participation credit, complete the exercises highlighted in red.

Homework