Dictionaries

A dictionary for your ideas

Lesson 7 of 20 · 7 min · Module 3: Working with collections

A dictionary connects a meaningful key to a value. It is useful when a list alone does not tell the whole story.

Start this lesson →

Free. No installation: you write and run the code in your browser, and it is checked automatically.

By the end, you’ll be able to…

  • Create a dictionary with meaningful keys
  • Read an optional value using get
  • Choose a suitable default

The idea

Create a dictionary with curly braces. Read a value using square brackets, such as profile["name"]. Use .get(key, default) when a key might be missing.

profile = {"name": "Alex", "lessons": 5}
print(profile["name"])

01Keys and values play different roles

In {"name": "Alex", "lessons": 5}, the keys describe what the values mean. Dictionary keys are looked up exactly, so spelling and capitalization matter.

02A default handles missing information

person.get("lessons", 0) returns the stored count when it exists and zero when it does not. It does not add a new key to person.

person = {"name": "Sam"}
print(person.get("lessons", 0))
Output
0

Your turn

Create profile with the keys "name": "Alex" and "lessons": 5. Define remaining(person) to return how many of 10 lessons remain, using zero when the lessons key is missing.

What the checks look for

  • Dictionary stores a name and lesson count
  • Five lessons remain for Alex
  • Handles a missing lessons key
  • Works with a different lesson count
Try it in the editor →

Take this with you

A dictionary connects meaning to data; a default makes an expected absence explicit.

Learn Python Foundations for free

20 short lessons with real code and instant checks.

See the whole course →