Skip to main content
Programming from zero

Group hosts by health status

mediumDictionaries

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.

TEXT
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:

TEXT
healthy:
- api-01
- db-01
unhealthy:
- cache-01
- web-01

Approach

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, then groups[status] = [], then groups[status].append(host).
  • Java: groups.containsKey(status) checks the keys, then groups.put(status, new ArrayList<>()), then groups.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}")