Course contentsLesson 9 of 13← Course overview
  1. 01Meet Python12 min
  2. 02Set up and run Python12 min
  3. 03Variables and data types15 min
  4. 04Strings and input15 min
  5. 05Decisions with conditionals15 min
  6. 06Repeat work with loops15 min
  7. 07Functions and return values18 min
  8. 08Work with lists16 min
  9. 09Dictionaries and tuples16 min
  10. 10Understand errors and exceptions14 min
  11. 11Read and write files16 min
  12. 12Modules and the standard library14 min
  13. 13Build a small data summary20 min

Python & data · Lesson 09

Dictionaries and tuples

Edit lesson

Describe a record with key-value pairs and group related values in tuples.

16 minProgress saves on this device
In this lesson
  • 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.

A dictionarypython
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.

Use a defaultpython
park = {"name": "Oak"}
visitors = park.get("visitors", 0)
print(visitors)  # 0

Visit 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.

Iterate over a recordpython
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,).

Unpack a tuplepython
location = (28.61, 77.21)
latitude, longitude = location
print(latitude, longitude)
Knowledge check

What happens when a missing dictionary key is accessed with square brackets?

Try first; feedback appears after you check.
Apply it

Your turn

Create a dictionary for a book with a title and page count. Print its title.

BUILT TOGETHER

Help make this explanation better.

Have a clearer explanation, a useful example, or a correction? Share it with the community.

Contributors

Be the first to add your name when you improve this lesson.

How to get credited
Previous lessonNext lesson