15/40
Part 3 of 7 · Grouping and countingLearn and do
setdefault and defaultdict make the empty list for you
The if-not-in step takes three lines. Python has two shorter ways:
# one dict method
by_host.setdefault(host, []).append(event)
from collections import defaultdict
# a dict that makes missing values
by_host = defaultdict(list)
by_host[host].append(event)
All three build the same dict. defaultdict(list) reads best when the whole job is grouping. It calls list() to make a value whenever you read a key that isn't there, and keeps it.
That's handy while grouping, and a trap afterwards. Just looking up a key adds it:
from collections import defaultdict
by_host = defaultdict(list)
print(by_host["no-such-host"])
print(dict(by_host))
[]
{'no-such-host': []}
When you only want to check, ask "other" in by_host or by_host.get("other").
In the editor, by_host is a defaultdict(list) with one event for web-1. Write quiet_hosts(by_host, hosts): the hosts, in the order given, that have no events. Check with in or get, so that by_host gains no keys.