Working with Text and Collections
Dictionaries and Key-Value Pairs
6 min read
Looking things up by name, not position
A list stores items in order: the first item is at index 0, the second at index 1. That works well for a shopping list. But what about a student record?
If you stored a student's data in a list like ["Priya", 17, "A", True], how would you know which item is the name and which is the grade? You'd have to remember that index 0 is the name, index 2 is the grade — fragile and hard to read.
Python's dictionary solves this by letting you label every piece of data with a key. Instead of position 0, you access the name with the label "name". Instead of position 2, you access the grade with "grade".
What is a dictionary?
A dictionary is a collection of key-value pairs. Every piece of data (the value) is attached to a label (the key).
Think of a real dictionary: you look up a word (the key) to find its definition (the value). Python dictionaries work the same way.
student = {
"name": "Priya",
"age": 17,
"grade": "A",
"passed": True
}
- Keys are on the left of the
:and are usually strings - Values are on the right and can be any type
Accessing values
Use square brackets with the key name to retrieve a value:
student = {
"name": "Priya",
"age": 17,
"grade": "A",
"passed": True
}
print("Student name:", student["name"]) # Priya
print("Grade:", student["grade"]) # A
Using .get() for safer access
If you try to access a key that doesn't exist, Python raises a KeyError and stops your program:
print(student["email"])
# KeyError: 'email'
.get() avoids this by returning None (or a default you specify) if the key is missing:
print(student.get("grade")) # A
print(student.get("email")) # None (no error)
print(student.get("email", "N/A")) # N/A (custom default)
What can be a key?
Not every type is allowed as a dictionary key. Keys must be immutable (unchangeable) — strings, numbers, and tuples all work:
mydict = {"one": 1, "two": 2} # string keys
mydict = {1: "one", 2: "two"} # number keys
points = {
(1, 2): 10,
(3, 4): 20,
} # tuple keys
Mutable types — like lists — can't be keys, because Python needs a key's value to never change once it's stored. Trying anyway raises an error:
mydict = {
([1, 2, 3], 4): "one",
}
# TypeError: unhashable type: 'list'
A tuple works as a key only if everything inside it is also immutable. A tuple containing a list is still not allowed.
Updating values
You can update a value by assigning to its key:
student["grade"] = "A+"
print("Updated record:", student)
If the key doesn't already exist, this adds a new key-value pair to the dictionary:
student["email"] = "priya@example.com"
print(student) # now has an "email" key
Using .update() for bulk changes
To update multiple keys at once — or add new ones — use .update():
product = {"name": "Notebook", "price": 4.5, "stock": 12}
product.update({"price": 4.99, "color": "blue"})
print("After update:", product)
# {'name': 'Notebook', 'price': 4.99, 'stock': 12, 'color': 'blue'}
Removing items
.pop(key) removes a key and returns its value:
product = {"name": "Notebook", "price": 4.99, "stock": 12}
removed = product.pop("stock")
print("Removed stock:", removed) # 12
print("Final product:", product)
# {'name': 'Notebook', 'price': 4.99}
If you don't need the removed value, del removes a key just as well:
del product["price"]
print(product)
# {'name': 'Notebook'}
Inspecting the dictionary
product = {"name": "Notebook", "price": 4.5, "stock": 12}
print("Keys:", list(product.keys()))
# ['name', 'price', 'stock']
print("Values:", list(product.values()))
# ['Notebook', 4.5, 12]
print("Items:", list(product.items()))
# [('name', 'Notebook'), ('price', 4.5), ('stock', 12)]
print("Has stock key?:", "stock" in product) # True
Looping through a dictionary
Looping directly over a dictionary gives you its keys, one at a time:
inventory = {"pen": 12, "notebook": 5, "eraser": 3}
for item in inventory:
print(item)
# pen
# notebook
# eraser
That's useful when you only need the keys. Most of the time, though, you want the values too — use .items() to loop through both keys and values at the same time:
inventory = {
"pen": 12,
"notebook": 5,
"eraser": 3
}
for item, count in inventory.items():
print(f"{item}: {count}")
Output:
pen: 12
notebook: 5
eraser: 3
Real-world use: display a product catalog, summarize inventory levels, print a user profile.
A complete example
Here's everything together — building a product record, modifying it, and reading it back:
product = {"name": "Notebook", "price": 4.5, "stock": 12}
print("Original product:", product)
print("Keys:", list(product.keys()))
print("Values:", list(product.values()))
print("Items:", list(product.items()))
product.update({"price": 4.99, "color": "blue"})
print("After update:", product)
print("Has stock key?:", "stock" in product)
print("Price with get():", product.get("price"))
removed = product.pop("stock")
print("Removed stock:", removed)
print("Final product:", product)
Output:
Original product: {'name': 'Notebook', 'price': 4.5, 'stock': 12}
Keys: ['name', 'price', 'stock']
Values: ['Notebook', 4.5, 12]
Items: [('name', 'Notebook'), ('price', 4.5), ('stock', 12)]
After update: {'name': 'Notebook', 'price': 4.99, 'stock': 12, 'color': 'blue'}
Has stock key?: True
Price with get(): 4.99
Removed stock: 12
Final product: {'name': 'Notebook', 'price': 4.99, 'color': 'blue'}
Dictionaries vs. lists
| List | Dictionary | |
|---|---|---|
| Created with | [] | {} |
| Items accessed by | Index number | Key name |
| Best for | Ordered sequences | Labeled data |
| Example | ["milk", "eggs", "bread"] | {"name": "Priya", "age": 17} |
Quick reference: common dictionary methods
| Method | What it does |
|---|---|
d["key"] | Access value by key |
d.get("key") | Access value safely (no error if missing) |
d["key"] = val | Set or update a value |
d.update({...}) | Update multiple keys at once |
d.pop("key") | Remove a key and return its value |
del d["key"] | Remove a key (no return value) |
d.keys() | Returns all keys |
d.values() | Returns all values |
d.items() | Returns all key-value pairs |
"key" in d | Checks if a key exists |
Key takeaway
Dictionaries store data as labeled key-value pairs, letting you look up information by name rather than position. They're perfect for structured records like user profiles, product data, or settings. Keys must be immutable — strings, numbers, or tuples — while values can be anything. The most important methods are .get() for safe access, .update() for bulk changes, .pop() (or del) for removal, and .items() for looping.
What's next?
You now have the core data structures covered: strings, lists, tuples, and dictionaries. The next step is teaching your programs to make decisions — responding differently depending on what the data says. That's what Python's if, elif, and else statements do.