Dictionaries

Quiz: counts toward finishing the lesson. Check: just for practice.

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 = {"apple": 4, "pear": 2}
stock["apple"] = 9
stock["plum"] = 1
size = len(stock)
apples = stock["apple"]

Predict what each variable holds after the program finishes. The program is not run for you. Change the values below to your predictions:

  • 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:

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:

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 = {"tea": 3, "milk": 2}
joined = ""
for item in prices:
    joined = joined + item
count = len(prices)

Predict what each variable holds after the program finishes. The program is not run for you. Change the values below to your predictions, and write strings with quotes:

  • 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:

As with lists, there are other operators, functions, and methods for working with dictionaries.

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.