Dictionaries – Storing Key-Value Pairs

Section Overview

Dictionaries are a powerful Python data structure that store data as key-value pairs. This allows you to organize and access information by unique keys rather than by index.

By the end of this section, you will be able to:

  • Create and access dictionaries
  • Add, modify, and remove key-value pairs
  • Iterate over dictionaries to access keys and values
  • Understand common use cases for dictionaries

Lesson 1: Creating Dictionaries

A dictionary is defined using curly braces {} with key-value pairs separated by colons.

Example:

person = {
    "name": "Alice",
    "age": 30,
    "city": "New York"
}

print(person)

Output:

{'name': 'Alice', 'age': 30, 'city': 'New York'}

Lesson 2: Accessing Values by Keys

Access a value by using its key inside square brackets or with .get():

print(person["name"])   # Outputs: Alice print(person.get("age")) # Outputs: 30 

Using .get() is safer because it returns None (or a default value) if the key doesn’t exist, instead of raising an error.


Lesson 3: Adding and Modifying Items

Add or update a key-value pair like this:

person["email"] = "alice@example.com"  # Adds a new key
person["age"] = 31                     # Updates existing key 

Lesson 4: Removing Items

Remove a key-value pair with del or .pop():

del person["city"]          # Removes the key 'city'
email = person.pop("email") # Removes and returns value for 'email' 

Lesson 5: Looping Through Dictionaries

You can loop through keys, values, or both:

for key in person:
    print(key)

for value in person.values():
    print(value)

for key, value in person.items():
    print(f"{key}: {value}")

Quiz: Check Your Understanding

1. How do you access the value associated with the key "name" in a dictionary?
Answer: dictionary["name"] or dictionary.get("name")


2. What happens if you try to access a key that doesn’t exist using square brackets?
Answer: Python raises a KeyError.


3. How do you add a new key-value pair to a dictionary?
Answer: dictionary[new_key] = new_value


4. True or False: The keys in a dictionary must be unique.
Answer: True


Practice Exercise: Phonebook

Create a dictionary that stores names and phone numbers. Then:

  1. Ask the user to enter a name
  2. Print the phone number if the name exists, or a message if it doesn’t

Starter code:

phonebook = {
    "Alice": "555-1234",
    "Bob": "555-5678",
    "Charlie": "555-8765"
}

name = input("Enter a name: ")

if name in phonebook:
    print(f"{name}'s phone number is {phonebook[name]}")
else:
    print(f"No phone number found for {name}")

Challenge: Allow the user to add a new name and phone number if it’s not found.