Skip to content
Lesson 7 of 10 · Python for Complete Beginners

Dictionaries

Look things up by key, count and group with dictionaries, and loop over them.

18 min

A dictionary stores key: value pairs. You look a value up by its key instead of by position:

python5 lines
ages = {"Ada": 36, "Grace": 45}
print(ages["Ada"])        # 36
ages["Alan"] = 41         # add a new pair
ages["Ada"] = 37          # change an existing one
del ages["Grace"]         # remove a pair

Keys are usually strings or numbers and must be unique. Asking for a key that is not there raises a KeyError. Two safe ways to ask:

python3 lines
"Linus" in ages            # False
ages.get("Linus")          # None, no error
ages.get("Linus", 0)       # 0, your own default

python4 lines
for name in ages:                      # keys
    print(name)
for name, age in ages.items():         # key and value together
    print(name, age)

ages.keys(), ages.values() and ages.items() give the three views.

The most useful dictionary idiom is counting how often things appear:

python4 lines
counts = {}
for letter in "banana":
    counts[letter] = counts.get(letter, 0) + 1
# {'b': 1, 'a': 3, 'n': 2}

Read the loop body as "the new count is the old count, or 0 if I have not seen it, plus one".

Reference

Dictionary methods you will use

d[k]

What it does
value for key k, or KeyError

d.get(k, default)

What it does
value, or default if missing

k in d

What it does
True if the key exists

d.items()

What it does
all (key, value) pairs, for looping

d.pop(k)

What it does
remove the pair and return its value

len(d)

What it does
number of pairs

Choose the container by how you will look things up.

List

Look up by
position (index)
Order matters
yes
Duplicates
allowed

Best for a sequence: steps, scores over time

Dictionary

Look up by
key
Order matters
keeps insertion order, but you look up by key
Duplicates
keys must be unique

Best for a lookup: price by product, count by word

Exercise4 checks
python

Write word_counts(text) that returns a dictionary counting how many times each word appears. Ignore capitals ("The the" counts as the twice) and split on whitespace.

Your code must satisfy

  • word_counts("a b a")→{"a":2,"b":1}simple
  • word_counts("The the THE")→{"the":3}case ignored
  • word_counts("")→[]empty
  • word_counts("to be or not to be")→{"to":2,"be":2,"or":1,"not":1}sentence
starter code2 lines
def word_counts(text):
    pass
Exercise3 checks
python

Write invert(d) that swaps keys and values: invert({"a": 1, "b": 2}) is {"1": "a", "2": "b"}.

Because JSON keys are text, the tests make the new keys strings: convert each old value with str().

Your code must satisfy

  • invert({"a": 1, "b": 2})→{"1":"a","2":"b"}two pairs
  • invert({})→[]empty
  • invert({"x": "red"})→{"red":"x"}words
starter code2 lines
def invert(d):
    pass
  • A dictionary maps unique keys to values: d[key], d[key] = value.
  • Use .get(key, default) or in when the key may be missing.
  • .items() loops over keys and values together.
  • Counting with d[k] = d.get(k, 0) + 1 is the idiom for frequencies.
Check yourself

Dictionary checks.

1Multiple choice

d = {"a": 1, "b": 2}. What is d["b"]?

  • A1
  • B2
  • C"b"
  • DKeyError
2Multiple choice

What does {"a": 1}.get("z", 0) return?

  • ANone
  • B0
  • CKeyError
  • D"z"
3Numeric answer

d = {"x": 5} then d["y"] = 7. What is len(d)?

4Multiple choice

Which is a good use of a dictionary?

  • AThe scores of a game, in the order played
  • BThe price of each product, looked up by name
  • CThe letters of a word
  • DA single number
5Fill the blanks

To loop over keys and values together, write for k, v in d.():

Capitalisation, spacing and punctuation are ignored when grading.

Practise this lesson, not just read it

In BiliMind the questions above are marked when you answer, the flashcards come back on a schedule, and the rest of Python for Complete Beginners is planned around your week. Free.