Python & data · Lesson 09
Dictionaries and tuples
Describe a record with key-value pairs and group related values in tuples.
- Read and update dictionary entries
- Handle missing keys
- Recognize when a tuple is useful
Helpful background: Understand variables, lists, and loops.
Store a record
A dictionary maps unique keys to values. Keys let you describe the meaning of each value, such as the name and number of visitors for a park.
Use a key in square brackets to read or update its value. Reading a missing key this way raises KeyError.
park = {"name": "Oak", "visitors": 42}
print(park["name"])
park["visitors"] = 45
print(park["visitors"])Handle a missing key
get() returns a default when a key is absent; without a supplied default, that value is None. Check whether a key is present when a missing value needs a different action.
Do not assume that a returned value is present merely because it is truthy: zero and empty strings can be valid values.
park = {"name": "Oak"}
visitors = park.get("visitors", 0)
print(visitors) # 0Visit keys and values
items() provides key-value pairs that can be unpacked in a loop. Dictionary insertion order is preserved, but use keys rather than relying on position to find a value.
park = {"name": "Oak", "visitors": 42}
for key, value in park.items():
print(key, value)Use a tuple
A tuple is an ordered collection whose items cannot be reassigned in place. It is useful for a small fixed group, such as coordinates. A tuple can still contain a mutable object.
A one-item tuple needs a trailing comma, as in (3,).
location = (28.61, 77.21)
latitude, longitude = location
print(latitude, longitude)What happens when a missing dictionary key is accessed with square brackets?
Your turn
Create a dictionary for a book with a title and page count. Print its title.
book = {"title": "The River", "pages": 120} print(book["title"])
BUILT TOGETHER
Help make this explanation better.
Have a clearer explanation, a useful example, or a correction? Share it with the community.
Be the first to add your name when you improve this lesson.
How to get credited