TutreNews Learn

Dictionaries and sets

Dictionaries

Goal: Store, read, update and loop over key-value pairs · 10 min

A dictionary maps keys to values: ages = {"Ada": 36, "Alan": 41}. You look values up by key, which is fast no matter how big the dictionary is.

ages["Ada"]               # 36
ages["Grace"] = 85        # add a new key
ages["Ada"] = 37          # change an existing value
del ages["Alan"]          # delete a key
"Ada" in ages             # True  (tests KEYS)
ages.get("Zoe", 0)        # 0     (safe lookup with a default)
len(ages)                 # number of pairs

Reading a missing key with ages["Zoe"] raises a KeyError; ages.get("Zoe") returns None (or a default you give) instead.

Looping:

for key in ages:                 # keys
for value in ages.values():      # values
for key, value in ages.items():  # both

Since Python 3.7 dictionaries remember insertion order. Keys must be immutable (strings, numbers, tuples), values can be anything, including lists and other dictionaries. Keys are unique: assigning to an existing key replaces the value.

Worked example: A phone book

  1. book = {"Ada": "123", "Alan": "456"}.
  2. book["Grace"] = "789" adds an entry; book.get("Zoe", "unknown") returns the default.
  3. items() gives pairs for a loop.
book = {"Ada": "123", "Alan": "456"}
book["Grace"] = "789"
print(book.get("Zoe", "unknown"))
for name, number in book.items():
    print(name, number)

Output:

unknown
Ada 123
Alan 456
Grace 789