Count how many servers are in each region
Problem statement
An inventory export gives the region of each server as a list. Count the servers in each region and print one line per region, in the order each region first appears, as region: count.
Examples
Example 1
Input: regions = ["us-east", "eu-west", "us-east", "ap-south", "us-east", "eu-west"]
Output: us-east: 3
eu-west: 2
ap-south: 1
Hints
Approach
Optimal
A dictionary is a natural fit for counting: each key is a region and each value is how many times you have seen it. Loop over the list, and for each region look up its current count with counts.get(region, 0), which returns 0 the first time, then store that plus one. Dictionaries in Python keep keys in the order they were first added, so printing with a loop over counts.items() gives the regions in first-seen order. .items() returns each key and value together, which you unpack into two loop variables.
regions = ["us-east", "eu-west", "us-east", "ap-south", "us-east", "eu-west"] counts = {}for region in regions: counts[region] = counts.get(region, 0) + 1 for region, count in counts.items(): print(f"{region}: {count}")Follow-up questions
- Print the regions sorted by count, highest first, using
sorted(counts.items(), key=lambda kv: kv[1], reverse=True).
Frequently asked questions
Yes, collections.Counter(regions) does this in one line. Writing it by hand first helps you understand what Counter does and how to adapt the pattern, for example to sum disk sizes per region instead of counting.
The first time a region appears, it has no entry, so reading it raises KeyError. .get(region, 0) supplies the starting value.