14/40
Part 3 of 7 · Grouping and countingLearn and do
Group by a computed key
The second pattern puts things that have something in common into one list each. The something is a key you compute from each item. The dict maps each key to its list.
A grouping dict maps each computed key to a list
Here's a log grouped by host:
events = ["web-1:timeout", "db-1:restart", "web-1:restart", "cache-1:timeout", "db-1:disk:full"]
by_host = {}
for line in events:
host, _, event = line.partition(":")
if host not in by_host:
by_host[host] = []
by_host[host].append(event)
for host, got in by_host.items():
print(host, got)
web-1 ['timeout', 'restart']
db-1 ['restart', 'disk:full']
cache-1 ['timeout']
The dict fills in one line at a time:
| Line | Key | What happens | The key's list |
|---|---|---|---|
| web-1:timeout | web-1 | a new key, a new list | [timeout] |
| db-1:restart | db-1 | a new key, a new list | [restart] |
| web-1:restart | web-1 | append | [timeout, restart] |
| cache-1:timeout | cache-1 | a new key, a new list | [timeout] |
| db-1:disk:full | db-1 | append | [restart, disk:full] |
Two details in that loop get people. The first is the split:
print("db-1:disk:full".split(":"))
print("db-1:disk:full".partition(":"))
['db-1', 'disk', 'full']
('db-1', ':', 'disk:full')
split(":") cuts at every colon. Unpack its three parts into two names, host, event = ..., and you get ValueError: too many values to unpack (expected 2). partition(":") cuts at the first colon only, and always returns three parts.
The second detail is the empty list for a new key.
Write by_host[host] = [event] on every line, in place of the append. How many of the 5 events are left at the end?
Pick an answer above to see the rest