Dictionaries map keys to values

A list finds things by position. A dictionary (dict) finds things by key. Think of a real dictionary: you look up a word (the key) and get its meaning (the value).

ages = {"Ana": 15, "Ben": 17}
print(ages["Ana"])    # 15

Curly braces, and each entry is key: value. Keys are usually strings or numbers, and each key appears only once.

Changing a dict:

  • ages["Cleo"] = 14 adds a new key, or replaces the value if the key already exists. Same syntax for both.
  • del ages["Ben"] removes a key.
  • "Ana" in ages checks whether a key exists (it does not search the values).

Asking for a key that is not there, like ages["Zed"], crashes with a KeyError. The safe version is ages.get("Zed", 0), which returns the default 0 instead of crashing. Without a default, get returns None.

Looping over a dict gives you its keys. To get keys and values together, use .items():

for name, age in ages.items():
    print(name, age)

Dicts remember the order you inserted things, so the loop goes in that order.

The classic dict move is counting: go through some data and keep a tally per item.

counts = {}
for word in words:
    counts[word] = counts.get(word, 0) + 1

First time a word shows up, get gives 0, so it becomes 1. Next time it becomes 2, and so on. This one pattern shows up everywhere, from word clouds to vote counting to "which emoji does my group chat use most".

Try it yourself

Edit it. Break it. Run it again.
ages = {"Ana": 15, "Ben": 17}
ages["Cleo"] = 14        # add
ages["Ben"] = 18         # update
print(ages)
print(ages.get("Zed", "unknown"))

for name, age in ages.items():
    print(f"{name} is {age}")

votes = ["pizza", "tacos", "pizza", "sushi", "pizza", "tacos"]
counts = {}
for v in votes:
    counts[v] = counts.get(v, 0) + 1
print(counts)
Ctrl/Cmd + Enter runs. Esc, then Tab, leaves the editor.

Your turn

Type it yourself. That is the whole trick.

1Phone book

Add "Dee" with the number "555-0199" to the phone book, change Ali's number to "555-0000", then print Ali's number and then Dee's number on two lines.

phones = {"Ali": "555-0101", "Bo": "555-0142"}
print(phones["Ali"])
Ctrl/Cmd + Enter runs. Esc, then Tab, leaves the editor.

2Letter counter

Write count_letters(text) that returns a dictionary mapping each character in text to how many times it appears. For example count_letters("hello") should return {"h": 1, "e": 1, "l": 2, "o": 1}.

def count_letters(text):
    counts = {}
    return counts
Ctrl/Cmd + Enter runs. Esc, then Tab, leaves the editor.

Code editor. Press Control or Command plus Enter to run the code. Tab indents; to move focus out of the editor, press Escape and then Tab.