A list finds things by position. Often you want to find them by name instead: a phone number by person, a price by product. For that Python has the dictionary, dict for short. It stores pairs: a key you look up and the value stored under it. Write it in curly brackets with a colon between each key and value.
Assigning to a key adds it, or replaces its value if it's already there. Keys are unique: a dict can't have the same key twice. del removes a pair, and key in d asks whether a key is there.
stock = {"pens": 10}
stock["paper"] = 200
stock["pens"] = 8
print(stock)
del stock["paper"]
print("paper" in stock)
Prints
{'pens': 8, 'paper': 200}
False
Looking up a key that isn't there stops with a KeyError. When a key might be missing, use get(): d.get(key) gives None instead of an error, and d.get(key, default) gives the default you choose.
A for loop over a dict goes through its keys, in the order they were added. items() gives you each key and value together, which you can unpack into two variables in the loop. keys() and values() give just one side.
scores = {"Ana": 12, "Ben": 9}
for name, score in scores.items():
print(name, score)
print(sum(scores.values()))
Prints
Ana 12
Ben 9
21
A classic use is counting: go through some data and add 1 to a key each time you see it. get(key, 0) handles the first time, when the key isn't there yet.
counts = {}
for word in "the cat and the hat".split():
counts[word] = counts.get(word, 0) + 1
print(counts)
Prints
{'the': 2, 'cat': 1, 'and': 1, 'hat': 1}
(split() breaks a string into a list of words; the next lessons use it a lot.) Values can be anything, including lists and other dicts, which is how most real data looks, for example a list of dicts, one per customer.