Previous Lesson Table of Contents Next Lesson

When you lookup a word in an actual dictionary, you find the word and its corresponding definition. You can say that the dictionary maps each word to a definition. The word in this case is called the key, and it has an associated value, or definition.

This mapping of keys to values is what defines a Python dictionary (or dict) object. Now they don’t necessarily have to be words and definitions. The keys can be any immutable Python object (same restriction as for sets). The values of a dict can be anything.

To create a dictionary, we create a comma-delimited group of key-value pairs surrounded by curly braces. By key-value pair, we mean key : value, where key is replaced by our actual key (e.g. a word), and value is replaced similarly.

Here is a more concrete example:

d = {1: 2, 2: "foo"}

Here, the key 1 maps to the value 2. Meanwhile, the key 2 maps to the value "foo".

Like list and set, dict is also mutable. To add a key-value pair to your dict, use the following syntax:

key = 3
value = 5

d[key] = value

This will output:

{1: 2, 2: 'foo', 3: 5}

Incidentally, this is the same way you can “index” into a dict by passing in the key between brackets like a list:


This will output:


It should be noted that if you attempt to add a key-value pair whose key already exists in the dict, the existing key-value pair will be overwritten with the new one.

Bonus: You might be wondering: can we do something similar with list?

l = [1, 2, 3]
l[0] = 5


Indeed, we can! This will output:

[5, 2, 3]

You can view (in some ways) a list as mapping the numbers from 0 to len(list) - 1 to list elements as values. Note though this syntax is only valid for overwriting elements in the list. You cannot add new ones.

Returning to dict, we can also remove key-value pairs using the pop method, which accepts any valid Python key as input and outputs the associated value:


This will output:

{2: 'foo', 3: 5}

What happens if we try to index or remove with keys that don’t exist?

invalid_key = "non-existent"


In both cases, we will get the following error:

KeyError: 'non-existent'

Finally, dict is also a collection (of key-value pairs), so we can use the len function from Lesson 9 to count the number of key-value pairs:


After the pop method call, this will output:


Let’s practice what we have learned with dict so far:

  • Create a dict with the following key-value pairs: "dog" and 2, "cat" and 3, "mouse", and 5. (solution)

  • Output the length of the dict. (solution)

  • Add the following key-value pair: "horse" and 6. Then modify the "dog" key to have a corresponding value of 7. Then delete the key "mouse". (solution)

  • Output the length of the modified dict. Then output the new value associated with the key "dog". (solution)

If you feel comfortable with dictionaries, feel free to move on to the next lesson!