Part 4: Dictionaries

Kerry Back, Rice University

Dictionaries

Dictionaries store data as key-value pairs.

Created with curly braces {}:

car = {
    "brand": "Toyota",
    "model": "Camry",
    "year": 2020,
    "color": "blue"
}

print(car)
{'brand': 'Toyota', 'model': 'Camry', 'year': 2020, 'color': 'blue'}

Think of it like a real dictionary: the key is the word, the value is the definition.

Practice: Creating Dictionaries

Exercise 1 (with Gemini): Ask Gemini to “write Python code that creates a dictionary with keys ‘name’, ‘age’, and ‘city’ and prints it”

Exercise 2 (on your own): Type person = {"name": "Alice", "age": 30} then print(person) and run it.

Accessing Dictionary Values

Access values using keys in square brackets:

print("Brand:", car["brand"])
print("Year:", car["year"])

# Check if a key exists
print("Has 'model':", "model" in car)
print("Has 'price':", "price" in car)
Brand: Toyota
Year: 2020
Has 'model': True
Has 'price': False

Unlike lists (indexed by position), dictionaries use meaningful keys like "brand" or "year".

Practice: Accessing Values

Exercise 1 (with Gemini): Ask Gemini to “write Python code that accesses the ‘model’ value from a car dictionary”

Exercise 2 (on your own): Type student = {"name": "Bob", "grade": 85} then print(student["name"]) and run it.

Dictionary Methods

Useful methods to work with dictionaries:

print("All keys:", list(car.keys()))
print("All values:", list(car.values()))
print("All items:", list(car.items()))
All keys: ['brand', 'model', 'year', 'color']
All values: ['Toyota', 'Camry', 2020, 'blue']
All items: [('brand', 'Toyota'), ('model', 'Camry'), ('year', 2020), ('color', 'blue')]
  • .keys() - returns all keys
  • .values() - returns all values
  • .items() - returns key-value pairs as tuples

Practice: Dictionary Methods

Exercise 1 (with Gemini): Ask Gemini to “write Python code that prints all keys from a dictionary”

Exercise 2 (on your own): Type d = {"a": 1, "b": 2} then print(list(d.values())) and run it.

Adding and Modifying

Add new key-value pairs or modify existing ones with assignment:

# Add a new key-value pair
car["price"] = 25000
print("After adding price:", car)

# Modify existing value
car["year"] = 2021
print("After updating year:", car)
After adding price: {'brand': 'Toyota', 'model': 'Camry', 'year': 2020, 'color': 'blue', 'price': 25000}
After updating year: {'brand': 'Toyota', 'model': 'Camry', 'year': 2021, 'color': 'blue', 'price': 25000}

Key point: If key exists → update value. If key doesn’t exist → create new pair.

Practice: Adding and Modifying

Exercise 1 (with Gemini): Ask Gemini to “write Python code that adds a new key ‘color’ to a car dictionary”

Exercise 2 (on your own): Type book = {"title": "Python"} then book["author"] = "Smith" then print(book) and run it.

Formatting Long Dictionaries

For readability, break dictionaries across multiple lines:

inventory = {
    "apples": 50,
    "bananas": 30,
    "oranges": 25,
    "grapes": 40
}

print(inventory)
{'apples': 50, 'bananas': 30, 'oranges': 25, 'grapes': 40}

Rule: Can break anywhere except before a comma.

Practice: Formatting

Exercise 1 (with Gemini): Ask Gemini to “write Python code that creates a multi-line dictionary with 4 items”

Exercise 2 (on your own): Create a dictionary on multiple lines for practice (no specific code required).

Lists vs. Dictionaries

Feature Lists Dictionaries
Structure Ordered sequence Key-value pairs
Access By index: list[0] By key: dict["key"]
Indexing Numeric (0, 1, 2…) Custom keys
Best For Sequences, order matters Lookups by name/ID
Examples Shopping list, scores Phone book, inventory

Lists vs. Dictionaries Examples

Use a list when you have a sequence:

test_scores = [85, 92, 78, 95]
print("First score:", test_scores[0])
First score: 85

Use a dictionary when you need named lookups:

student = {"name": "Alice", "age": 20, "gpa": 3.8}
print("Student name:", student["name"])
Student name: Alice

Practice: Lists vs Dictionaries

Exercise 1 (with Gemini): Ask Gemini to “explain when to use a list versus a dictionary in Python”

Exercise 2 (on your own): Type scores = [85, 92, 78] then print(scores[0]) and run it.

The len Function

len() returns the length of strings, lists, and dictionaries:

my_list = [1, 2, 3, 4, 5]
my_dict = {"a": 1, "b": 2, "c": 3}
my_string = "hello"

print("List length:", len(my_list))
print("Dict length:", len(my_dict))  # counts key-value pairs
print("String length:", len(my_string))
List length: 5
Dict length: 3
String length: 5

For dictionaries, len() returns the number of key-value pairs.

Practice: len() Function

Exercise 1 (with Gemini): Ask Gemini to “write Python code that finds the length of a dictionary”

Exercise 2 (on your own): Type items = [1, 2, 3, 4, 5] then print(len(items)) and run it.

Summary

  • Dictionaries store key-value pairs using {}
  • Access values by key: dict["key"]
  • Methods: .keys(), .values(), .items()
  • Add/modify with assignment: dict["new_key"] = value
  • Use lists for sequences, dictionaries for named lookups
  • len() works on strings, lists, and dictionaries

Dictionaries are perfect when you need to look up information by name or ID!