Dictionaries and sets
Counting, grouping and comprehensions
Goal: Use dictionaries to count and group data and build them with comprehensions · 12 min
Three patterns appear all the time.
1. Counting. How often does each item occur?
counts = {}
for word in words:
counts[word] = counts.get(word, 0) + 1
.get(word, 0) returns the current count (or 0 if the word is new), and we store it back plus one.
2. Grouping. Collect items under a key:
groups = {}
for word in words:
groups.setdefault(len(word), []).append(word)
setdefault(key, []) inserts an empty list the first time and returns the list so we can append to it.
3. Dictionary comprehension: {key: value for item in iterable}:
squares = {n: n * n for n in range(1, 4)} # {1: 1, 2: 4, 3: 9}
lengths = {w: len(w) for w in ["hi", "world"]} # {'hi': 2, 'world': 5}
Sorting a dictionary by value uses sorted with a key function; the result is a list of pairs:
sorted(counts.items(), key=lambda pair: pair[1], reverse=True)
Nested dictionaries hold structured records: user = {"name": "Ada", "langs": ["en", "de"], "address": {"city": "Berlin"}}; read user["address"]["city"]. Python also offers collections.Counter for counting, but writing the loop once shows how it works.
Worked example: Counting letters
- Text "banana". Start with an empty dictionary.
- For each letter: counts[letter] = counts.get(letter, 0) + 1.
- Result: {"b": 1, "a": 3, "n": 2}, in order of first appearance.
counts = {}
for letter in "banana":
counts[letter] = counts.get(letter, 0) + 1
print(counts)Output:
{'b': 1, 'a': 3, 'n': 2}