Dictionaries: Records with Named Parts

Many things a program keeps track of come in parts that belong together: a book has a title, an author and a year. A list holds its items by position, so you would have to remember that position 0 is the title and position 2 is the year. A dictionary lets you give each part a name and ask for it by that name, which makes code easier to read and harder to get wrong.

Keys paired with values

A dictionary is a collection of pairs. Each pair has a key, the name you look something up by, and a value, the thing stored under that name. You write a dictionary between curly brackets { }. Inside, each pair is the key, a colon, then the value, and commas separate the pairs:

book = {"title": "Dune", "author": "Frank Herbert", "year": 1965}
print(book)

This dictionary has three pairs. The key "title" is paired with the value "Dune", and the key "year" with the whole number 1965. Values can be any type: strings, numbers, booleans, even lists. Keys are usually strings, and whole numbers work too. When you print a dictionary, Python shows it in the same written form, with strings in single quotes:

{'title': 'Dune', 'author': 'Frank Herbert', 'year': 1965}

The difference from a list is how you reach a value. A list numbers its items by position, counting from zero. A dictionary has no positions to count: every value is found through its key. The same three facts look like this in each:

A list: reached by position
IndexItem
0'Dune'
1'Frank Herbert'
21965
A dictionary: reached by key
KeyValue
'title''Dune'
'author''Frank Herbert'
'year'1965

In the list, nothing says that item 2 is a year; you have to remember it. In the dictionary, the key says it. Two rules follow from looking values up by key. First, the keys in one dictionary are unique: there can be only one "title", because a lookup must lead to exactly one value. Second, a key has to match exactly. "Title" and "title" are different strings, so they are different keys.

A dictionary still remembers the order its pairs were added in, and printing it or looping over it follows that order. That order is for your convenience when reading output; it is never how you reach a value.

True or false?

For the book above, book[0] gives the first pair of the dictionary.

False. A dictionary has no positions. book[0] looks for the key 0, and since there is no such key, Python stops with an error.

One dictionary cannot hold two entries with the same key.

True. Keys are unique within a dictionary, so every key leads to exactly one value.

The keys "Year" and "year" refer to the same entry.

False. A key must be equal to the stored key, and strings with different capital letters are not equal.

Reading, adding and changing entries

One key with its value is called an entry. To read an entry, write the dictionary's name followed by the key in square brackets. This is the same bracket notation a list uses for an index, but what goes inside is a key:

book = {"title": "Dune", "author": "Frank Herbert", "year": 1965}

print(book["title"])
print(f"Published in {book['year']}")
Dune
Published in 1965

Inside the f-string the key is written in single quotes, book['year']. Since Python 3.12, double quotes would work there too, but single quotes make it easier to see where the f-string ends, and they also work in older versions of Python.

Changing an entry and adding a new one are the same step: put the key in square brackets on the left of an equals sign and the value on the right. If the key is already in the dictionary, its old value is replaced. If it is not, a new entry is added at the end. No method like append is needed.

book["year"] = 1966      # "year" exists: its value is replaced
book["pages"] = 412      # "pages" is new: an entry is added
print(book)
{'title': 'Dune', 'author': 'Frank Herbert', 'year': 1966, 'pages': 412}

The changed entry keeps its place, and the new one appears last. The dictionary still has only one "year": storing under a key that is in use forgets the old value.

True or false?

Writing book["year"] = 1966 when "year" already exists adds a second year entry.

False. Keys are unique, so assigning to an existing key replaces its value. The dictionary still has one year.

The same kind of line, d[key] = value, both adds new entries and changes existing ones.

True. Python checks whether the key is there: if it is, the value is replaced, and if not, a new entry is added.

When a key is missing

Reading is stricter than writing. Asking for a key the dictionary does not have is an error, the way an index past the end of a list is. Python stops the program, and the last line of its message names the error and the key it could not find:

book = {"title": "Dune", "author": "Frank Herbert", "year": 1965}
print(book["pages"])
KeyError: 'pages'

A KeyError is the dictionary version of the IndexError a list gives. The key in quotes is exactly what your code asked for, so it is the first thing to compare against the keys the dictionary really has: a misspelled key or a capital letter in the wrong place shows up right there.

When a key may or may not be there, check first. The word in asks whether a key is in a dictionary, and gives True or False, so it fits straight into an if. Its opposite, not in, gives the reverse.

if "pages" in book:
    print(f"{book['pages']} pages")
else:
    print("No page count for this book.")

For the book above, without a "pages" entry, this prints No page count for this book. and the program goes on. Note that in looks only at the keys: "year" in book is True, while 1965 in book is False, because 1965 is a value and not a key.

True or false?

For the book above, 1965 in book gives True.

False. in checks the keys of a dictionary. 1965 is a value, and no key equals 1965, so the result is False.

Reading a missing key with square brackets stops the program with a KeyError.

True. Unlike assignment, reading never creates an entry. Python raises KeyError and names the key it was asked for.

A list of dictionaries

One dictionary describes one thing. To describe many things of the same kind, put one dictionary per thing in a list. Each dictionary is a record, and all the records use the same keys, so the same code can read any of them:

books = [
    {"title": "Dune", "author": "Frank Herbert", "year": 1965},
    {"title": "Emma", "author": "Jane Austen", "year": 1815},
    {"title": "Beloved", "author": "Toni Morrison", "year": 1987},
]

It helps to picture this as a table. Each item of the list is a row, and each key is a column:

books
Index'title''author''year'
0'Dune''Frank Herbert'1965
1'Emma''Jane Austen'1815
2'Beloved''Toni Morrison'1987

The rows are reached by position, because the outer collection is a list. The parts of a row are reached by key, because each row is a dictionary. To read one value you use both, from left to right: books[1] is the whole dictionary for Emma, and books[1]["author"] then looks up a key in that dictionary and gives 'Jane Austen'.

  • books a list
  • [1] by position
  • Emma's record a dictionary
  • ["author"] by key
  • 'Jane Austen' a string
  • books to [1]
  • [1] to Emma's record
  • Emma's record to ["author"]
  • ["author"] to 'Jane Austen'

Most of the time you do not pick rows by number at all; you loop over them. A for loop over the list gives you one whole dictionary each round, and inside the block you read its parts by key:

for book in books:
    print(f"{book['title']} by {book['author']} ({book['year']})")
Dune by Frank Herbert (1965)
Emma by Jane Austen (1815)
Beloved by Toni Morrison (1987)

The loop body runs three times, and each time book refers to the next record. Because every record has the same keys, book['title'] works in every round. A record that lacked one of those keys would stop the loop with a KeyError when its turn came. That is why the records in one list are given the same keys.

The usual list patterns work on records too. This loop collects the titles of the books published before 1900 into a new list:

old_titles = []
for book in books:
    if book["year"] < 1900:
        old_titles.append(book["title"])
print(old_titles)
['Emma']

True or false?

In for book in books, the name book refers to one whole dictionary in each round.

True. The loop walks the list item by item, and every item is a dictionary, so book is one record at a time.

books["title"] gives the title of the first book.

False. books is a list, so it takes a position, not a key. Pick a record first, as in books[0]["title"].

books[2]["year"] gives 1987.

True. books[2] is the third record, the one for Beloved, and its "year" entry is 1987.