Dictionaries

Dictionary Data Types

Python has a built-in data type called a dictionary. A dictionary stores key-value pairs. For example:

The first column has the keys and the second column has their associated values (the extra spaces that align the columns and colons only make it easier to read, and are not required). Each key can only have one value, but the same value can be used for multiple keys. Dictionaries, like lists, are mutable (you can change them after you create them). Unlike lists, though, you cannot look up an element by its position. You still use square brackets, but you put the key inside them, and you get back that key's value.

It's easy to add a new key-value pair:

Or to change an existing key-value pair:

Check your understanding. Predict the result. Notice which assignment changes a value and which adds a pair.

stock: dict[str, int] = {"apple": 4, "pear": 2}
stock["apple"] = 9
stock["plum"] = 1
size: int = len(stock)
apples: int = stock["apple"]

Predict what each variable holds after the program finishes. The program is not run for you. Replace each None in the box below with your prediction, and give each variable a type hint, like name: type = value. Then press Run to find out if you are right. Write text in quotes, like "abc". Write a list in square brackets, like [1, 2, 3].

  • final_size is the value of size at the end
  • final_apples is the value of apples at the end
Hint 1

Assigning to a key that already exists replaces its value. Assigning to a new key adds a pair.

You can delete an entry using del:

Printing a dictionary shows all of its key-value pairs:

Asking a dictionary for a key it does not have stops the program with a KeyError, much as asking a list for an index it does not have gives an IndexError.

"Idaho" is not a key in this dictionary, so Python reports a KeyError that names the missing key. Add "Idaho" : "Boise" to the dictionary and run it again.

Check your understanding. Predict the result. Each program stops with an error. Name the error for each one.

# first program
ages: dict[str, int] = {"Ana": 31, "Bo": 27}
print(ages["Cy"])

# second program
scores: list[int] = [90, 85]
print(scores[2])

Set first_error and second_error to the error names, written as strings between quotes, and give each a type hint. Python error names end in Error, and capital letters matter.

Hint 1

A dictionary is looked up by key and a list by position. Each error is named for the thing that was missing.

Type hinting with dictionaries

A type hint states the type a variable is expected to hold. You can add one to a dictionary. For state_capitals, it looks like this:

state_capitals: dict[str, str] = {
    "Washington" : "Olympia",
    "Oregon"     : "Salem",
    "Idaho"      : "Boise",
    "Montana"    : "Helena"
}

The state_capitals variable is declared as a dict[str, str], meaning a dictionary with keys of type str and values of type str.

The keys in a dictionary must be immutable (unchangeable, like strings and numbers), but the values can be of any type. The keys do not all have to be the same type. You can even nest dictionaries. Here's a dictionary with some string values and an integer value. To allow more than one type, use the | operator in the hint.

You can declare an empty dictionary like so:

An empty dictionary still needs a type hint, because it needs to say what it could hold. Here we chose str keys and int values.

You can use in and not in to test whether a key is in a dictionary:

You can use len to get the number of key-value pairs in a dictionary:

A for loop goes through a dictionary's keys:

A loop returns the keys in the order they were added.

Check your understanding. Predict the result. Look at what the loop variable holds on each pass.

prices: dict[str, int] = {"tea": 3, "milk": 2}
joined: str = ""
for item in prices:
    joined = joined + item
count: int = len(prices)

Predict what each variable holds after the program finishes. The program is not run for you. Replace each None in the box below with your prediction, and give each variable a type hint, like name: type = value. Then press Run to find out if you are right. Write text in quotes, like "abc". Write a list in square brackets, like [1, 2, 3].

  • final_joined is the value of joined at the end
  • final_count is the value of count at the end
Hint 1

A for loop over a dictionary gives you one thing per pass. Is it a key or a value?

The clear method makes a dictionary empty:

Recall: click each blank to check yourself

Name the error for each mistake.

  • A variable that was never assigned:
  • The wrong kind of value, like "a" + 1:
  • The right type but a bad value, like int("twelve"):
  • Dividing by zero:
  • A key that is not in a dictionary:
  • An index past the end of a list:
  • A function that calls itself with no base case:

Quizzes

  1. Make a dictionary called eng_to_span where the keys are the English words "one" through "ten", and the corresponding values are their Spanish translations.
  1. Using the dictionary from #1, write a loop that prints both the key and value of each key-value pair. For example the first iteration of the loop should print one uno.
  1. Write a function named some_squares that takes a positive integer parameter and returns a dictionary where the keys are the integers from 1 through the value of the parameter, and the corresponding values are the squares of those integers. For example, if it's passed 3, then the dictionary should contain the following key-value pairs: {1: 1, 2: 4, 3: 9}.

Projects

Practice what you learned in your own editor. Each project has its own page.