Lists, dictionaries, strings
Dictionaries
Goal: Store and look up key–value pairs · 9 min
A dictionary maps keys to values: ages = {"Ada": 36, "Linus": 21}.
- Look up:
ages["Ada"]→ 36. Missing key → KeyError; safer:ages.get("Bob", 0)returns 0. - Add or change:
ages["Bob"] = 30. - Loop:
for name, age in ages.items(): "Ada" in ageschecks for a key.
Dictionaries are ideal for counting: counts[word] = counts.get(word, 0) + 1. Since Python 3.7 they remember insertion order.
Worked example: Counting words
- Split the sentence into words.
- For each word increase its counter (start at 0 with get).
- Result:
{'to': 2, 'be': 2, 'or': 1, 'not': 1}
counts = {}
for w in "to be or not to be".split():
counts[w] = counts.get(w, 0) + 1
print(counts)Output:
{'to': 2, 'be': 2, 'or': 1, 'not': 1}