TutreNews Learn

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 ages checks 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

  1. Split the sentence into words.
  2. For each word increase its counter (start at 0 with get).
  3. 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}