Specialty Digest

Global English editionLearners’ Study Dashboard — in development
The Knowledge Library for All

Flashcards: open the module flashcards (end-of-module review with workplace questions).

Online Courses / University Track / Python from Zero

Module 4 · Lesson 3 · Core

Dictionaries: looking things up by key

Make a dictionary, look up a value by key, add and update pairs and avoid a KeyError.

  • 50 minutes
  • Serves O4
  • Assumes M4.L2

Phase 1: Prepare

Step 1 Warm-up recall

From M4.L2: which tool gives the largest item in a list?

Private: nothing you type here is sent or stored.

Step 2 Learning goal

By the end of this lesson you can:

  • create a dictionary and look up a key (Foundation);
  • add and update pairs (Core);
  • avoid a KeyError (Core).

Phase 2: Teach

Step 3 A familiar example

A price list is read by name: what does rice cost? You do not ask for the third line. A dictionary works like this, by key.

Step 4 Clear explanation

A dictionary stores key and value pairs in curly brackets. You ask by key and get the value.

price = {"tea": 2, "rice": 5}
print(price["rice"])
price["milk"] = 3
print(len(price))
price["tea"] = 4
print("tea" in price)
for item in price:
    print(item, price[item])
5
3
True
tea 4
rice 5
milk 3
Key"rice"DictionarypriceValue5
A dictionary stores pairs. You look up a value by its key, not by a position.
CodeMeaningResult for price = {"tea": 2, "rice": 5}
price["rice"]look up a key5
price["milk"] = 3add a pairprice has 3 pairs
"tea" in priceis the key present?True
price.get("egg", 0)look up with a default0

Assigning to an existing key updates it; assigning to a new key adds a pair. Looking up a key that is not there stops the program with a KeyError. Check with in first, or use get with a default. Keys must be written exactly: "Tea" and "tea" are different keys. Since Python 3.7, a loop visits keys in the order they were added.

Step 5 Worked example (4 marks)

For stock = {"a": 10, "b": 4}, run stock["b"] = stock["b"] - 1 then find stock["b"] and len(stock).

  1. stock["b"] is 4, so 4 - 1 = 3 is stored. (1 mark)
  2. stock["b"] is now 3. (1 mark)
  3. There are still two keys: len is 2. (1 mark)
  4. Answer: 3 and 2. (1 mark)

Go deeper: the professor's notes

A dictionary stores only what exists, and looks it up by key.
Key

Name.

Value

Data.

Missing

KeyError.

KeynameLookupdict[key]ValuedataMissingget
Dictionary

Sparse

StyleStores
full tableevery empty space too
dictionaryonly the pairs present

At work: A large survey

Most answers are empty.

  1. Store only answered pairs.
  2. Use get for the rest.

What a careful practitioner decides. Use a dictionary when most combinations are empty.

Phase 3: Practise

Step 6 Learner practice (instant-marked)

1. In {"tea": 2, "rice": 5}, the value for "rice" is:

2. Looking up a missing key gives:

3. price["milk"] = 3 for a new key:

4. price.get("egg", 0) returns 0 when:

Phase 4: Close

Step 7 Recap

  • A dictionary maps keys to values; you ask by key.
  • Assigning to a key adds or updates it.
  • A missing key is a KeyError; use in or get.

Step 8 Exit ticket (ungraded)

Write a dictionary of three items and prices, then add a fourth.

Private: nothing you type here is sent or stored.

Step 9 Go further (Extension)

Write a program that asks for an item name and prints its price, or Not stocked.

In industry: The Netflix Prize data

The data in the Netflix Prize held about 100 million ratings from some 480 thousand users on about 18 thousand movies. The matrix of users and movies was about 99 percent empty.

Link to this lesson. Data with mostly empty spaces is kept as pairs for the things that exist, which is how a dictionary works.

Source: Feuerverger, He and Khatri, Statistical Significance of the Netflix Challenge

Common mistakes

MistakeWhy it fails
Using position numbersUse keys.
Different case in key"Tea" is not "tea".
Not checking before lookupUse in or get.

Limits. Keys must be of a fixed kind such as text or numbers; this lesson uses text keys.

Flashcards for this lesson (3)

Tap a card to reveal the answer. Read the question, answer it aloud or in writing first, then check yourself against the explanation.

Card 1 of 3 · How do you search a list?
FlagFalseLoopeach itemSetTrue
Search

Use in for a quick yes or no, or a loop with a flag set True when an item passes the test. Search a list of orders for any over a limit.

Card 2 of 3 · What is a dictionary?
KeynameLookup[key]Valuedata
Dictionary

Key and value pairs in curly brackets. You ask by key and get the value. A price list by item name is the classic use.

Card 3 of 3 · How do you add or update a dictionary entry?
New keyaddsOld keyupdateslenpairs
Add or update

Assign to the key: a new key adds a pair; an existing key updates its value. Stock levels are updated this way after each sale.

Review with flashcards

Test yourself on this module with workplace flashcards and detailed answers.

Open the module flashcards