Dictionaries

Introduction

A dictionary stores pairs: a key and its value. Instead of asking for "the item at position 2", you ask for "the value for this key", like looking up a name in a phone book.

Lists find things by position, but much of the world is organised by name: a word and its meaning, a student and their mark. A dictionary finds a value directly from its key, however large the collection grows.

How it works

Keys and values

ages = {"Rahim": 21, "Karim": 22}
ages["Nadia"] = 20
print(ages["Rahim"])
print(len(ages))
Open in compiler

The objects panel draws the dictionary as a two-column table, keys on the left and values on the right.

  • ages["Rahim"] looks up a value by its key.
  • ages["Nadia"] = 20 adds a new pair, or replaces the value if the key already exists.
  • len(ages) counts the pairs. Each key appears only once.

Looping over pairs

stock = {"pens": 12, "pencils": 30}
for item, amount in stock.items():
    print(item, amount)
Open in compiler

items() gives each key together with its value, so the loop gets two variables per round.

Syntax

ages = {"Rahim": 21}
ages["Nadia"] = 20
ages.get("Karim", 0)
"Rahim" in ages
for name, age in ages.items():
    print(name, age)

Example

text = "a b a c b a"
counts = {}
for word in text.split():
    counts[word] = counts.get(word, 0) + 1
print(counts)
Open in compiler

This counts how often each word appears. counts.get(word, 0) gives the current count, or 0 if the word has not been seen yet; adding 1 and storing it back updates the count. Step through and watch rows appear and change in the table: a reaches 3, b 2 and c 1.

Line by line

  1. text is the sentence to count.
  2. counts = {} starts with an empty dictionary.
  3. text.split() gives the words, and the loop visits each one.
  4. counts.get(word, 0) gives the count so far, or 0 the first time.
  5. Adding 1 and storing it back updates that word's count.
  6. print(counts) shows the finished tally.

Expected result

{'a': 3, 'b': 2, 'c': 1}

In the real world

A dictionary can count votes, store settings or hold a cache of answers. JSON, the format used by almost every web service, maps directly onto Python dictionaries and lists.

Common mistakes

  • ages["Tanvir"] for a key that does not exist is a KeyError. Check with "Tanvir" in ages, or use ages.get("Tanvir").
  • Using a list as a key is a TypeError; keys must not change, so use strings, numbers or tuples.
  • Expecting two values for one key: assigning to an existing key replaces the old value.

Best practices

  • Use get or in when a key might be missing.
  • Use strings, numbers or tuples as keys.
  • Use items() when you need keys and values together.

Summary

A dictionary stores key and value pairs and finds values directly by key. Assigning to a key adds or replaces it, get supplies a default, and items() loops over both at once.

Practice

Read a line of words and print the word that appears most often. If several words tie, print the one that appeared first.

Quick check

1. With d = {'a': 1}, what does d['a'] = 5 do?
2. What does d.get('z', 0) give when 'z' is not a key?
3. What does len({'x': 1, 'y': 2}) give?

Key takeaways

  • A dictionary finds a value directly, with no searching.
  • get gives a default instead of an error.
  • Each key appears only once.

Practice problems for this lesson

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.