Dictionaries
Key-Value Storage in Python
In the previous unit, we explored ranges, sets, and tuples. Now let's look at dictionaries, Python's way of storing data as key-value pairs.

What Is a Dictionary?
A dictionary stores items as key-value pairs. You look up values by their keys, not by position. This makes dictionaries fast for retrieving specific data.
person = {
"name": "Alice",
"age": 25,
"city": "New York"
}
Each key (like "name") maps to a value (like "Alice"). Keys must be unique and immutable.
Creating and Accessing
Create a dictionary with curly braces {}, separating keys and values with colons.
person = {"name": "Alice", "age": 25}
print(person["name"]) # Outputs: Alice
To change a value, assign to its key:
person["age"] = 26
To add a new key-value pair, just assign it:
person["city"] = "Boston"
Common Methods
Dictionaries have several useful methods.
person = {"name": "Alice", "age": 26, "city": "Boston"}
# Get all keys
print(person.keys()) # dict_keys(['name', 'age', 'city'])
# Get all values
print(person.values()) # dict_values(['Alice', 26, 'Boston'])
# Get key-value pairs as tuples
print(person.items()) # dict_items([('name', 'Alice'), ...])
# Safely get a value (returns None if key doesn't exist)
print(person.get("name")) # Alice
print(person.get("unknown")) # None
# Update with another dictionary
person.update({"city": "LA", "state": "CA"})
# Remove and return a value
city = person.pop("city") # Returns "LA"
The get() method is especially useful because it won't raise an error if the key doesn't exist, unlike bracket notation.
Project: Command-Based Drawing
Let's use a dictionary to map commands to Turtle functions. The user types commands like "forward" or "left", and the dictionary tells us which function to call.
import turtle
screen = turtle.Screen()
screen.setup(width=800, height=600)
screen.bgcolor("white")
t = turtle.Turtle()
# Map commands to turtle functions
commands = {
'forward': t.forward,
'backward': t.backward,
'left': t.left,
'right': t.right,
'color': t.color
}
while True:
cmd = input("Command (or 'exit'): ")
if cmd == 'exit':
break
if cmd not in commands:
print("Unknown. Try:", list(commands.keys()))
continue
value = input("Value: ")
if cmd != 'color':
value = int(value)
commands[cmd](value)
t.hideturtle()
turtle.done()
The dictionary commands maps strings like "forward" to actual functions like t.forward. When the user enters a command, we look it up in the dictionary and call the corresponding function with the provided value.
This pattern is powerful because it's easy to extend. Add 'pensize': t.pensize to the dictionary, and you've added a new command without changing any other code.
In the next unit, we'll learn how to read from and write to files in Python.