Python 3.4Code walkthrough9 parts

Dictionaries

Map keys to values: counting, grouping, lookup.

Loading your progress…Next: 3.5 Strings

In this lesson9 parts

  1. 01Finding a price by its name
  2. 02Keys, values and lookup
  3. 03A missing key: KeyError, in and get
  4. 04Adding, updating and removing
  5. 05keys, values, items, and looping over a dictionary
  6. 06What can be a key: hashable keys, and nested dictionaries
  7. 07Counting with a dictionary, and Counter
  8. 08Grouping with a dictionary, and defaultdict
  9. 09Recap, your challenge, and next

Key terms

The words this lesson introduces, each in one line. The module’s glossary collects them all.

Counter
A dictionary that counts; a missing key counts zero. Counter(votes).most_common(1) gives [('tea', 3)]. From collections.
defaultdict
A dictionary that creates a missing key's value when the key is read: defaultdict(list) creates []. From collections.
dictionary
A collection of key value pairs, looked up by key: {"Pasta": 12.50, "Salad": 8.25}. Its type is dict.
key
What a dictionary looks a value up by, such as "Pasta" in the menu. Each key appears once, and must be hashable.
key value pair
One entry of a dictionary: a key and its value, written "Pasta": 12.50.
nested dictionary
A dictionary whose values are dictionaries: cafe["drinks"]["Juice"].
value
What a dictionary stores for each key, such as 12.50 for "Pasta". Values can be anything, including lists and dictionaries.

Quiz 5 questions

Your first pick on each question is the one that counts, and a right one earns a coin. Getting one wrong here is how the lesson sticks.

Practice

Problems to solve in your own notebook. Each states the problem, not the steps: working out the steps is the exercise. Level A applies the lesson, B combines it with earlier ones, C stretches it.

The self-checking notebook for this lesson is Notebook 2 · Sets and Dictionaries.

Common mistakes

What you will see when it goes wrong, why it happens, and the fix.

Where it’s used

Where this lesson’s ideas turn up in real work.