Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

A dictionary is a data structure used to store mappings from unique keys to values.

fav_color = {"akap1204": "lavender", "ktgower": "pink", "aronacho": "fuchsia", "ksuhas16": "green"}
squares = {2: 4, 3: 9, 5: 25, -5: 25, -2: 4, -3: 9}
atomic_number = {"H": 1, "Fe": 26, "Au": 79}
food_price = {"Taco": 3.25, "Burrito": 7.5, "Chips": 2.5, "Guac": 4.75}
empty_dict = {} # An empty dictionary

Retrieve and modify information in a dictionary using square bracket syntax:

Practice: Food prices

Given the dictionary food_price = {"Taco": 3.25, "Burrito": 7.5, "Chips": 2.5, "Guac": 4.75}, which statement will result in an error?

food_price[2.5]
food_price["Guac"] = 3
del food_price["taco"]
food_price[2.5] = "Chips"

Iteration

By default, if we attempt to loop over a dictionary, we loop over only its keys in the order they were initially added to the dictionary.

for uwnetid in fav_color:
    print(uwnetid, "fav color is", fav_color[uwnetid])

Avoid iterating over a dictionary. A very common mistake is to use a loop when you only needed to look up a single value. Only iterate over a dictionary if you need to modify or access the values associated with every key. To find a single person’s favorite color, just look it up directly: fav_color["aronacho"].

Dictionaries also have methods to retrieve collections of their keys, values, or key-value pairs:

Practice: Counting words

Write code that uses a dictionary to count how many times each unique word appears in the phrase below:

phrase = "how much wood could a woodchuck chuck if a woodchuck could chuck wood"