Dictionaries introduction

Dictionaries

A dictionary (dict) stores key-value pairs — instead of looking things up by position (like a list), you look them up by a key you choose:

ages = {"ada": 36, "alan": 41, "grace": 85}

ages["ada"]       # 36
ages["grace"]      # 85

Adding and updating

ages["katherine"] = 33   # adds a new key
ages["ada"] = 37          # updates an existing key

Checking membership and missing keys

Looking up a key that doesn't exist raises KeyError — usually not what you want:

ages["nobody"]   # KeyError: 'nobody'

Check first with in:

if "nobody" in ages:
    print(ages["nobody"])
else:
    print("not found")

Or use .get(key, default), which returns default instead of raising if the key is missing:

ages.get("nobody", 0)     # 0 -- not found, so the default is returned
ages.get("ada", 0)         # 37 -- found, default is ignored

.get() is especially handy for counting, a pattern you'll use constantly:

counts = {}
for word in ["cat", "dog", "cat"]:
    counts[word] = counts.get(word, 0) + 1
# counts is {"cat": 2, "dog": 1}

Each time through the loop, .get(word, 0) returns the current count (or 0 the first time that word is seen), and adding 1 bumps it — all in one line, with no separate "is this word already in the dict?" check needed.

Iterating a dictionary

for key in ages:
    print(key)

for key, value in ages.items():
    print(key, value)

for value in ages.values():
    print(value)

.items() is what you'll reach for most often — it gives you both the key and the value together on each iteration.

Since Python 3.7, dictionaries remember the order keys were inserted — iterating always visits them in that same order, which is a detail you'll rely on in a couple of the problems ahead.