Dictionaries: look things up by key

Dictionaries & Sets, lesson 1 of 5

🗂️ Dictionaries & Sets, lesson 1 of 5

Dictionaries: look things up by key

Map keys to values, like a phone book or a price list.

9 min

1 exercise

2 quizzes

0/3 solved

Getting Python ready… examples can run in a moment.

A dictionary (dict) maps keys to values, like a menu maps dishes to prices. You find a value by its key, not by its position:

prices = {"apple": 0.5, "bread": 2.25}
prices["bread"]   # 2.25

Keys are unique. Assigning to a key adds it if it's new, or replaces its value if it exists.

Example

A price list

Add a price for "coffee", then print just that price.

Asking for a key that isn't there raises a KeyError. Two safe ways to look things up:

  • key in d checks whether a key exists.
  • d.get(key, default) returns the default (or None) instead of crashing.
Example

KeyError

Dictionary keys are case-sensitive too: stock["Apples"] fails the same way.

Example

.get() to the rescue

in checks keys, not values. Pears are in the dictionary even though there are 0 of them.

Quiz

What does this print?

Remove a key with del d[key], or with d.pop(key), which also returns the value.

Example

Contacts

What happens if you del a name that isn't there?

Quiz

Which of these can NOT be used as a dictionary key?

Exercise

Update the inventory

Update inventory:

  1. Add "cherries" with a count of 30.
  2. You sold 2 bananas: subtract 2 from its count.
  3. Remove "apples" completely.
  4. Set grapes to the grape count using .get() with a default of 0.