Please enable JavaScript to use CodeHS

Python Tutorial

Dictionaries in Python

A list numbers its items. A dictionary labels them. Store key-value pairs like names and phone numbers, then look anything up instantly by its key.

python ~20 min Beginner friendly
The Big Idea

What is a dictionary?

A dictionary is a data structure that stores key-value pairs. It works just like a real dictionary: you look up a word (the key) and you get its definition (the value). In a list you grab items by their position number, called an index. In a dictionary you grab items by their key instead.

You create a dictionary with curly brackets. This one is empty:

main.py
my_dictionary = {}

You can also start a dictionary with some key-value pairs already inside. Here is a tiny phone book. Each name is a key, and each phone number is that key's value:

main.py
my_dictionary = {
    "Tracy": "314-1592",
    "Karel": "123-4567"
}

Every pair follows the same pattern:

"Tracy"key
:colon
"314-1592"value
,comma
  • The key is on the left and its value is on the right.
  • The key and value are separated by a colon :
  • Multiple key-value pairs are separated by a comma.

The Fine Print

Keys and values can be different types

The keys and values in one dictionary do not all have to be the same data type. We can add the pair 225: 15 to our phone book even though the other entries are strings:

main.py
my_dictionary = {
    "Tracy": "314-1592",
    "Karel": "123-4567",
    225: 15
}

A key and its own value can be different types too: 225: "perfect square" is a perfectly valid pair (pun intended, since 15 × 15 = 225).

One important rule: a key cannot be a mutable (changeable) data type like a list or a set. A value can be. So "scores": [90, 85] is fine, but [90, 85]: "scores" would crash your program.

Look It Up

Reading a value by key

To read a value, put its key in square brackets after the dictionary's name: dictionary_name[key]. It is like turning a key in a lock. Each key opens exactly one value:

main.py
print(my_dictionary["Karel"])
print(my_dictionary[225])
Console
123-4567
15

Heads up: if you ask for a key that is not in the dictionary, Python stops your program with a KeyError. Try it in the playground below to see exactly what that looks like.

Make Changes

Adding, updating, and deleting pairs

Inserting a key-value pair

To add a new pair, use the same square-bracket pattern with an equals sign: dictionary_name[key] = value. Let's add another pair to my_dictionary:

main.py
my_dictionary[256] = 16

Now 256: 16 is a key-value pair in my_dictionary.

Updating a value

What if Karel gets a new phone number? Assign a new value to a key that already exists, and the old value is replaced:

main.py
# assigns the value "653-5897" to "Karel"
my_dictionary["Karel"] = "653-5897"
print(my_dictionary["Karel"])
Console
653-5897

Notice: adding and updating use the exact same code. If the key is new, Python adds a pair. If the key already exists, Python overwrites its value. Keys are unique, so a dictionary can never hold two pairs with the same key.

Deleting a pair

To remove a pair completely, use the del keyword: del my_dictionary["Tracy"]. The key and its value both disappear from the dictionary.


Interactive

Dictionary playground

Meet menu, a dictionary for a snack stand. Each food name is a key, and each price is its value. Use the controls to look up, add, update, and delete pairs, and watch the dictionary and the Python code change live:

Snack stand menu

dict
Python >>> menu Try a control below!

Look up a value

menu[key]

Add or update a pair

menu[key] = value

Delete a pair

del menu[key]

Is It In There?

Checking keys with in

Before you look up a key, you can check whether the dictionary has it. The in keyword gives you True if the key exists and False if it does not. This is a great way to avoid a KeyError:

main.py
if "Karel" in my_dictionary:
    print("Found Karel!")
else:
    print("No Karel here.")
Console
Found Karel!

Try it against the playground's menu dictionary. Type any key and see the answer update as you type:

in checker
"" in menu  →   True

Yes! "burger" is one of the keys in menu right now.

Good to know: in checks the keys, not the values. If menu is {"burger": 5.99}, then "burger" in menu is True, but 5.99 in menu is False.


Visit Every Pair

Looping over a dictionary

A for loop can visit every key in a dictionary, one at a time, using the same in keyword. Inside the loop, use each key to grab its value:

main.py
my_dictionary = {
    "Tracy": "314-1592",
    "Karel": "123-4567",
    225: 15
}

for key in my_dictionary:
    print(my_dictionary[key])
Console
314-1592
123-4567
15

You can read this loop out loud as: "for every key in my_dictionary, print out that key's value." The loop variable key holds each key in turn, and my_dictionary[key] looks up its value.

Want the keys too? Print both by passing the key and the lookup to print(): print(key, my_dictionary[key]) prints lines like Tracy 314-1592.

Put It Together

The full example

This program uses everything you just learned: it creates a dictionary, inserts a new pair, then loops over the dictionary and prints each value:

main.py
# Creates a dictionary with 3 initial values
my_dictionary = {
    "Tracy": "314-1592",
    "Karel": "123-4567",
    225: 15
}

# Inserts another key-value pair into the dictionary
my_dictionary[256] = 16

# Iterates through the dictionary and prints each value
for key in my_dictionary:
    print(my_dictionary[key])
Console
314-1592
123-4567
15
16

Your Turn

Practice problems

1

Explore the Example

Start from the full example program above and make three changes:

  • Insert a new key-value pair.
  • Assign one of the keys a different value.
  • Change the print statement in the for loop so it prints the key in addition to its value.
solution.py
my_dictionary = {
    "Tracy": "314-1592",
    "Karel": "123-4567",
    225: 15
}

my_dictionary[256] = 16

# 1. Insert a new key-value pair
my_dictionary["Tina"] = "867-5309"

# 2. Give an existing key a different value
my_dictionary["Karel"] = "653-5897"

# 3. Print the key AND its value
for key in my_dictionary:
    print(key, my_dictionary[key])
Console
Tracy 314-1592
Karel 653-5897
225 15
256 16
Tina 867-5309

Notice that updating "Karel" did not move it or add a second "Karel". The pair stays where it was, with a new value. Only brand-new keys add new pairs.

2

Build Your Own Dictionary

Create your own dictionary from scratch. It can be a phone book, a collection of square roots, a weekly dinner menu... the possibilities are endless! Master the basics by completing each task:

  • Create a dictionary with 2-4 initial values.
  • Insert 2 more key-value pairs.
  • Change the value of one of the keys.
  • Use a for loop to print out each key-value pair.
solution.py
# Create a dictionary with a few values
dinner_menu = {
    "Monday": "tacos",
    "Tuesday": "pizza",
    "Wednesday": "soup"
}

# Insert new key-value pairs
dinner_menu["Thursday"] = "pasta"
dinner_menu["Friday"] = "sushi"

# Change the value of a key
dinner_menu["Wednesday"] = "burgers"

# Use a for loop to print out each key-value pair
for day in dinner_menu:
    print(day, "->", dinner_menu[day])
Console
Monday -> tacos
Tuesday -> pizza
Wednesday -> burgers
Thursday -> pasta
Friday -> sushi

Code

A dictionary example

Dictionaries store key-value pairs. This program keeps track of a small address book.


Check Yourself

Quick quiz

1. Given ages = {"Tracy": 12, "Karel": 9}, what does print(ages["Karel"]) print?

2. Which line adds the pair "shake": 3.75 to the dictionary menu?

3. menu already contains "fries": 2.49. What happens after menu["fries"] = 2.99?

Keep learning Python

Dictionaries label your data with keys. Next, compare them with lists, which number their items, and tuples, which lock their items in place.