Group hosts by health status
Problem statement
Grouping goes one step past counting. Instead of storing a number under each key, you store a list. The key is the health status, and the list holds every host with that status. For each host, find the list for its status (creating an empty one the first time), then add the host to it.
Common mistake: adding to a list that does not exist yet.
Wrong: groups[status].append(host) (on the first host with that status)The first time a status appears, groups[status] has no list to add to, so Python crashes with a KeyError. Create the empty list first, only when the key is new.
Your task: given the health status of each host, {"api-01": "healthy", "cache-01": "unhealthy", "db-01": "healthy", "web-01": "unhealthy"}, group the hosts by status. Print each status followed by its hosts, one per line, indented with -.
Expected output:
healthy: - api-01 - db-01unhealthy: - cache-01 - web-01Approach
Loop over the hosts. For each one, make sure its status has an empty list, then add the host:
- Python:
if status not in groups:checks the keys, thengroups[status] = [], thengroups[status].append(host). - Java:
groups.containsKey(status)checks the keys, thengroups.put(status, new ArrayList<>()), thengroups.get(status).add(host). - C++:
groups[status].push_back(host)is enough, because[]creates an empty vector for a new key.
Note on order: as in the last problem, Python and Java's LinkedHashMap keep insertion order and C++'s std::map sorts by key. The sample data is already in alphabetical order, so all three print the same thing.
DSA connection: grouping items under a shared key appears in many hash map problems.
status_by_host = {"api-01": "healthy", "cache-01": "unhealthy", "db-01": "healthy", "web-01": "unhealthy"}
groups = {}
for host in status_by_host:
status = status_by_host[host]
if status not in groups:
groups[status] = []
groups[status].append(host)
for status in groups:
print(f"{status}:")
for host in groups[status]:
print(f" - {host}")