Reading Values

A dictionary is only useful if you can get the values back out. To read a value, write the dictionary's name and then the key in square brackets:

book = {"title": "The Hobbit", "author": "J. R. R. Tolkien", "pages": 310}

print(book["title"])
print(book["pages"])
The Hobbit
310

It looks like reading an element of a list, names[0], but there's a key in the brackets instead of an index. A dictionary has no indexes: you find each value by its key, just as you find a word in a dictionary by the word itself, not by its position.

book["title"] is a value like any other. You can store it in a variable, calculate with it or put it in an f-string:

book = {"title": "The Hobbit", "author": "J. R. R. Tolkien", "pages": 310}

pages_read = 100
print(f"{book['title']} by {book['author']}")
print("Pages left:", book["pages"] - pages_read)
The Hobbit by J. R. R. Tolkien
Pages left: 210

Look at the quotes in the f-string: the keys are in single quotes, book['title']. The f-string itself is in double quotes, and older versions of Python would think that the next double quote ends it. Since version 3.12, Python also understands f"{book["title"]}", but with single quotes inside, your code works in any version.

What if you read a key that isn't in the dictionary? Python can't find it, and the program ends with a KeyError:

book = {"title": "The Hobbit", "author": "J. R. R. Tolkien", "pages": 310}

print(book["year"])
Traceback (most recent call last):
  File "<exec>", line 3, in <module>
KeyError: 'year'

The last line says what went wrong: a KeyError, and the key that Python didn't find, 'year'. The book has no year. The line above it tells you on which line of the program it happened. Watch out for these causes too:

  • Uppercase and lowercase letters matter, as they do in variable names: book["Title"] ends with KeyError: 'Title'.
  • A dictionary has no indexes, so book[0] ends with KeyError: 0.

So when you see a KeyError, check how you wrote the key. In one of the next exercises, you'll learn how to check whether a key is there before you read it.

Instructions

The program ends with a KeyError. Read the last line of the error message, then fix the key in print() so that the program prints the book's title, The Hobbit.

Below, print the sentence The Hobbit has 310 pages. Don't type the title and the number yourself: read them from the dictionary, for example in an f-string.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

2/9