Unit 4 • Lesson 6

Dictionaries and Key-Value Pairs

Overview

Dictionaries store data in pairs that map keys to values, making them ideal for representing relationships between data. You'll learn how to create, access, and modify them to model structured information such as user profiles or settings, providing fast lookups by key.

Beginner 20–25 min

What You Will Learn in This Lesson

By the end of this lesson, you will know:

  • What dictionaries are: Understand how dictionaries store key-value pairs.
  • Creating dictionaries: Learn how to create and populate dictionaries.
  • Accessing values: Discover how to retrieve values using keys.
  • Modifying dictionaries: Learn how to add, change, and remove key-value pairs.

Why This Matters

Dictionaries are like real-world dictionaries - you look up a word (key) to find its definition (value). In programming, dictionaries let you store and quickly retrieve data by meaningful labels. Instead of remembering that index 0 is the name and index 1 is the age, you can use "name" and "age" as keys. This makes your code much more readable and easier to work with!

Step 1: What Is a Dictionary?

A dictionary is a collection of key-value pairs. Each key maps to a specific value, like a real dictionary where words (keys) map to definitions (values).

Creating Dictionaries
# Dictionary with key-value pairs
student = {
    "name": "Alice",
    "age": 20,
    "grade": "A"
}

print(student)  # Output: {'name': 'Alice', 'age': 20, 'grade': 'A'}
1

Curly Braces

Dictionaries are created using curly braces {}. This tells Python you're creating a dictionary.

2

Key-Value Pairs

Each item in a dictionary is a key-value pair, written as "key": value. The key and value are separated by a colon.

3

Commas

Key-value pairs are separated by commas. The last pair can optionally have a trailing comma.

Key Concept: Dictionaries are unordered (in older Python versions) or ordered (in Python 3.7+), but the important thing is that you access values by their keys, not by position. Keys must be unique and immutable (like strings, numbers, or tuples), while values can be anything!

Mini Practice #1: Creating Dictionaries

Try It Yourself

Try creating a dictionary:

Press Run to see output

What happened? You created a dictionary with three key-value pairs. Notice how each key (like "name", "age", "city") is paired with a value. Dictionaries are perfect for storing related information where each piece of data has a meaningful label. Instead of remembering positions, you use descriptive keys!

Step 2: Accessing Dictionary Values

You access dictionary values using their keys, not indices:

Accessing Values
student = {"name": "Alice", "age": 20, "grade": "A"}

print(student["name"])   # Output: Alice
print(student["age"])    # Output: 20
print(student["grade"])  # Output: A

How It Works

Use square brackets with the key name to access a value. Unlike lists where you use numeric indices, dictionaries use meaningful keys. If you try to access a key that doesn't exist, Python will raise a KeyError. You can also use the get() method which returns None (or a default value) if the key doesn't exist!

Step 3: Adding and Modifying Dictionary Entries

You can add new key-value pairs or modify existing ones:

Modifying Dictionaries
student = {"name": "Alice", "age": 20}

# Add a new key-value pair
student["grade"] = "A"

# Modify an existing value
student["age"] = 21

print(student)  # Output: {'name': 'Alice', 'age': 21, 'grade': 'A'}
1

Adding Entries

To add a new key-value pair, simply assign a value to a new key: dictionary["new_key"] = value. If the key doesn't exist, it's created.

2

Modifying Entries

To change an existing value, assign a new value to the same key: dictionary["key"] = new_value. This overwrites the old value.

3

Removing Entries

Use del dictionary["key"] or dictionary.pop("key") to remove a key-value pair.

Mini Practice #2: Working with Dictionaries

Try It Yourself

Try accessing and modifying dictionary values:

Press Run to see output

What happened? You accessed dictionary values using their keys and added a new key-value pair. Notice how much clearer this is than using indices - book["title"] is much more readable than book[0]. Dictionaries make your code self-documenting because the keys describe what the values represent!

Step 4: Dictionary Keys and Values

Dictionary keys must be immutable (like strings, numbers, or tuples), while values can be any type:

Different Key and Value Types
# Keys can be strings, numbers, or tuples
mixed_dict = {
    "name": "Alice",        # String key
    1: "one",              # Number key
    (2, 3): "coordinates"  # Tuple key
}

print(mixed_dict["name"])      # Output: Alice
print(mixed_dict[1])          # Output: one
print(mixed_dict[(2, 3)])     # Output: coordinates

Remember: Keys must be immutable types (strings, numbers, tuples). Lists cannot be keys because they're mutable. Values can be anything - strings, numbers, lists, dictionaries, or any other data type!

End-of-Lesson Exercises

Exercise 1: Create and Access a Dictionary

Create a dictionary called person with keys "name", "age", and "city" with values "Alice", 25, and "Boston" respectively. Print the name and age using dictionary access.

Use curly braces and colons to create key-value pairs, then access using square brackets.

Write your code above and click "Check Answer" to verify it's correct.

Exercise 2: Modify a Dictionary

Create a dictionary called car with "brand": "Toyota" and "model": "Camry". Add a new key "year" with value 2020, then change "model" to "Corolla". Print the final dictionary.

Use assignment to add new keys and modify existing ones.

Write your code above and click "Check Answer" to verify it's correct.