Skip to contentSkip to navigation

Module 04 · Lesson 01

Dictionaries & Hash Maps

Look values up by name instead of position with dictionaries: add, change and remove entries, read safely with get(), loop over keys, values and items, and count things.

  • About 8 minutes
  • Builds on earlier lessons
  • 12-question quiz at the end

What you will learn

  • Keys and values
  • Look up safely
  • Count with a dictionary
  • Watch a backpack fill

Look things up by name

A dictionary pairs each key with a value, like a word with its meaning. You find a value by its key, not by its position.

  • Keys and values

    Curly brackets, a colon in each pair: ages = {"Ana": 14, "Bo": 12}.

  • Look up

    ages["Ana"] gives 14. ages.get("Cy", 0) gives 0 instead of an error when the key is missing.

  • Change

    ages["Cy"] = 11 adds or replaces a pair. pop() and del take one out.

  • Loop

    for name, age in ages.items(): visits every pair.

Lookups all around you

Whenever you find something by its name, a dictionary is a good fit.

  • ContactsA name is the key and the phone number is the value.
  • InventoriesEach item a player carries maps to how many they have.
  • TranslationsAn English word maps to the same word in another language.
  • Settings{"volume": 7, "dark_mode": True} keeps every option under a clear name.

Storing under a key

This line adds or changes one pair. Tap each part to see its job.

Part 1 of 4

Tap any part of the code below, or press Next.1 of 4 explored

dictionary:An existing dictionary, for example stock = {"pears": 2}.

Look up and update

Pick an example, change it, then press Run. Say what you expect to see before you press.

Example 1 of 6Look up

Brackets need the key to exist. get() lets you choose a fallback.

Your turn: Add Peru and its capital, Lima, then look it up again.

Python
capitals = {"France": "Paris", "Japan": "Tokyo", "Kenya": "Nairobi"}
print(capitals["Japan"])
print(capitals.get("Peru", "not saved yet"))
Output
Press Run to see what it prints.

Watch a backpack fill up

Press Step to run one line at a time. Watch keys appear and values change in the names box.

Ready. Press Step to run the first line.

  1. inventory = {"sword": 1}
  2. inventory["potion"] = 3
  3. inventory["potion"] -= 1
  4. inventory["shield"] = inventory.get("shield", 0) + 1
  5. print(inventory)
  6. print(len(inventory), "kinds of item")

Output so far

Nothing printed yet.

What Python does

Python reads the program from the top. Nothing has run yet.

Names

None yet.

Quick guesses

Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.

Question 1 of 6

1.The same key twice: what prints?

d = {"a": 1, "a": 2}
print(d)

0 of 6 answered

Common dictionary misconceptions

Each card is something beginners often believe. Tap it to see what Python really does.

Misconception 1 of 4

Notes

Everything above, in words. Open it when you want the full explanation.

Read the notesOpen

Looking values up by key

A dictionary stores key-value pairs. You write it in curly braces, with a colon between each key and its value and commas between pairs.

Try it 1: edit me, then Run
ages = {"Ana": 14, "Bo": 12, "Cy": 15}
print(ages["Bo"])          # 12
print(len(ages))           # 3
Output
Press Run to see what it prints.

You read a value with square brackets and the key, not a position. Keys are usually strings, but numbers and tuples work too. Values can be anything, including lists and other dictionaries. Each key appears at most once; values may repeat.

Adding, changing and removing

Dictionaries are mutable. Assigning to a key adds it if it is new and replaces its value if it already exists.

Try it 2: edit me, then Run
stock = {"apples": 5}
stock["pears"] = 3         # new key: added
stock["apples"] = 8        # existing key: replaced
stock["apples"] += 2       # update from the old value
del stock["pears"]         # remove a key
print(stock)               # {'apples': 10}
Output
Press Run to see what it prints.

pop(key) removes a key and returns its value, which is useful when you want both. update(other) copies every pair from another dictionary in, replacing values for keys that already exist.

Missing keys

Reading a key that is not there raises KeyError. There are two calm ways to deal with that.

Try it 3: edit me, then Run
prices = {"tea": 2.5, "cake": 3.0}
if "coffee" in prices:
    print(prices["coffee"])
print(prices.get("coffee"))        # None
print(prices.get("coffee", 0))     # 0, the default you chose
Output
Press Run to see what it prints.

A KeyError is not a bug in Python; it is Python telling you that your program assumed something that was not true. Typos in keys are the usual cause, and keys are case sensitive, so "Tea" and "tea" are different keys. Printing the dictionary, or list(d) for just its keys, usually shows the problem at once. in checks whether a key exists; it does not look at the values. get(key) returns the value, or None if the key is missing, and get(key, default) returns your default instead. Use square brackets when a missing key is a real error you want to hear about, and get() when missing is normal.

Looping

A for loop over a dictionary gives its keys. The methods keys(), values() and items() give views of the keys, the values, or both as pairs. Dictionaries remember the order in which keys were added, so loops visit them in that order.

Try it 4: edit me, then Run
scores = {"Ana": 82, "Bo": 95, "Cy": 77}
for name in scores:
    print(name)
for name, score in scores.items():
    print(f"{name}: {score}")
print(sum(scores.values()) / len(scores))
Output
Press Run to see what it prints.

items() with unpacking, for key, value in d.items(), is the loop you will write most. To visit keys in alphabetical order, loop over sorted(scores), which sorts the keys.

Do not add or remove keys while looping over the same dictionary; Python raises RuntimeError. Changing the value of an existing key during the loop is fine.

The counting pattern

Counting how often each thing appears is one of the most common jobs in programming, and dictionaries make it short. For each item, look up its current count with a default of 0 and add one.

Try it 5: edit me, then Run
votes = ["tea", "coffee", "tea", "juice", "tea"]
counts = {}
for drink in votes:
    counts[drink] = counts.get(drink, 0) + 1
print(counts)              # {'tea': 3, 'coffee': 1, 'juice': 1}
Output
Press Run to see what it prints.

A close relative is grouping, where each key holds a list. setdefault(key, []) returns the existing list for a key, or inserts and returns a new empty list if the key is missing, so you can append in one line.

Try it 6: edit me, then Run
words = ["apple", "avocado", "banana", "blueberry", "cherry"]
by_letter = {}
for word in words:
    by_letter.setdefault(word[0], []).append(word)
print(by_letter["b"])      # ['banana', 'blueberry']
Output
Press Run to see what it prints.

What can be a key

Keys must be hashable: values that cannot change, such as strings, numbers and tuples of them. Python turns each key into a number called a hash and uses it to find the value immediately, which is why lookups stay fast even in a dictionary with a million entries. A list cannot be a key, because it could change after being stored, which would make its hash wrong; trying raises TypeError: unhashable type: 'list'. Use a tuple instead, for example (row, column) as the key for a grid square.

Building dictionaries

Besides writing one out, you can build a dictionary with dict(). dict(name="Ana", age=14) uses keyword arguments, and dict(zip(keys, values)) pairs up two lists. An empty dictionary is {}. Copying works like lists: b = a shares one dictionary, and a.copy() makes an independent one.

Merging two dictionaries

Settings are a common case for merging: a program has defaults, and a user's choices override some of them. defaults | choices builds a new dictionary with every key from both, where the right side wins for keys they share. defaults.update(choices) does the same but changes defaults in place. Both leave the keys that only one side has untouched.

Try it 7: edit me, then Run
defaults = {"theme": "light", "font": 14, "sound": True}
choices = {"theme": "dark"}
settings = defaults | choices
print(settings)    # {'theme': 'dark', 'font': 14, 'sound': True}
Output
Press Run to see what it prints.

Dictionary or list?

Use a list when order or position is what matters and the items are all the same kind of thing. Use a dictionary when you look things up by a name or an id, or when each value has a label. Many programs combine both: a list of dictionaries is a table of records, which the nested data lesson explores.

Syntax

The general shape of the statements in this lesson.

syntax.py
d = {"a": 1, "b": 2}     d = {}     d = dict(a=1, b=2)
d["a"]                   # KeyError if missing
d.get("z")   d.get("z", 0)
d["c"] = 3   d["a"] += 1   del d["b"]   d.pop("c")
"a" in d                 # checks keys
for k in d:   for v in d.values():   for k, v in d.items():
counts[x] = counts.get(x, 0) + 1
groups.setdefault(key, []).append(item)
Output
Press Run to see what it prints.

Worked examples

Read the problem, run the code, then read why it works.

Example 1 of 2

A small phone book

Beginner

Store three contacts, add a new one, change a number, then look up a name that exists and one that does not without crashing.

Python
phone = {"Ana": "0711 111", "Bo": "0722 222", "Cy": "0733 333"}
phone["Dee"] = "0744 444"
phone["Bo"] = "0799 999"
for name in ["Bo", "Eve"]:
    print(name, phone.get(name, "not found"))
print(sorted(phone))
Output
Press Run to see what it prints.

Predict first

How it works(open after your guess)

Assigning to "Dee" adds a contact and assigning to "Bo" replaces the old number. get() with a default handles the missing name politely. sorted(phone) sorts the keys, giving an alphabetical list of names.

Common pitfalls

Mistakes people make with this topic, and what to write instead.

Pitfall 1 of 3

Reading a missing key with brackets

Spot the bug

Can you see what is wrong? Run it to watch it go wrong, then open the fix.

Buggy code: run it
stock = {"apples": 5}
print(stock["pears"])
Output
Press Run to see what it prints.
Show what goes wrong and the fix

What happens

KeyError: 'pears'

Write this instead

stock = {"apples": 5}
print(stock.get("pears", 0))

Why it happens

Square brackets require the key to exist.

In the real world

Where this shows up in software people use every day.

  1. A cafe order tally

    Hospitality

    At the end of a shift, a cafe till counts how many of each drink was sold and works out the takings from a price list.

    Why Python fits

    One dictionary is a fixed price list and the other is built by counting. Keys connect the two: each drink name looks up its price.

    Python
    prices = {"tea": 2.0, "latte": 3.2, "juice": 2.5}
    orders = ["latte", "tea", "latte", "juice", "latte", "tea"]
    sold = {}
    for drink in orders:
        sold[drink] = sold.get(drink, 0) + 1
    takings = 0
    for drink, count in sold.items():
        takings += count * prices[drink]
        print(f"{drink}: {count}")
    print(f"Takings: {takings:.2f}")
    Output
    Press Run to see what it prints.

Key takeaways

Tick each one you could explain to a friend.

0 of 5

Common questions

Guess the answer first, then open it.

Are dictionaries ordered?

Yes. Since Python 3.7 they keep the order in which keys were first added. Changing a value does not move a key.

How do I sort a dictionary by its values?

Build a list of (value, key) tuples and sort it, as in the second worked example. A later course shows a shorter way with key=.

What is the difference between {} and set()?

{} is an empty dictionary. An empty set has to be written set(), which the next lesson covers.

Can two keys have the same value?

Yes. Values can repeat freely, as in {"Ana": 14, "Bo": 14}. Only the keys must be unique, because each key has to point to exactly one value.

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

Where to go next

The quiz and the Lab live on their own pages, so this lesson stays about learning.

Finished this lesson?

Create an ID or sign in to save your progress across devices.

Create ID to save
Lessons done in this module0/4 complete
Quiz

Check what you learned

12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.

Lab

Keep going in the Lab

7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.

Review

Spaced review

Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.

This lesson at a glance

The 8 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.

What else you can search for and explore

Curious to go further? Each card opens a web search in a new tab.

References

Look things up here whenever you need the exact details.