Group hosts by health status
Problem statement
A health check returns a dictionary of host to status. Turn it around into a dictionary of status to a list of hosts, then print one line per status, in first-seen order, with the hosts separated by commas.
Examples
Example 1
Input: health = {"web-01": "up", "web-02": "down", "db-01": "up", "cache-01": "down", "web-03": "up"}
Output: up: web-01, db-01, web-03
down: web-02, cache-01
Hints
Approach
Optimal
Loop over health.items() to get each host and its status together. The new dictionary groups uses the status as its key and a list of hosts as its value. The first time a status appears there is no list yet, so groups.setdefault(status, []) creates an empty one and returns it; on later passes it returns the existing list. You then .append(host) to that list. Finally, ", ".join(hosts) turns each list into a readable line. Grouping like this is how you build summaries such as "which hosts are down".
health = {"web-01": "up", "web-02": "down", "db-01": "up", "cache-01": "down", "web-03": "up"} groups = {}for host, status in health.items(): groups.setdefault(status, []).append(host) for status, hosts in groups.items(): print(f"{status}: {', '.join(hosts)}")Follow-up questions
- Print
All hosts healthyif there is nodownkey ingroups. - Also print how many hosts are in each group.
Frequently asked questions
Yes: if status not in groups: groups[status] = [] followed by groups[status].append(host). It is longer but does exactly the same thing, and may be easier to read at first.