Skip to main content
Programming from zero

Count how many servers are in each region

mediumDictionaries

Problem statement

Counting how often each value appears is a classic dictionary job. Use the region name as the key and the running count as the value. For each server, look up its region's current count (defaulting to 0 if the region is new), add 1, and store it back.

To print the results, you loop over the dictionary. A plain for region in counts loop gives you the keys, and you look up each count from there. The last problem in this section covers looping over keys and values together.

Common mistake: starting a count without a default.

TEXT
Wrong: counts[region] = counts[region] + 1

The first time a region shows up, counts[region] does not exist yet, so Python crashes with a KeyError. Reading the current count with a default of 0 (from the last problem) fixes it.

Your task: given regions = ["ap-south", "eu-west", "us-east", "eu-west", "us-east", "us-east"], count how many servers are in each region and print one line per region in the form <region>: <count>.

Expected output:

TEXT
ap-south: 1
eu-west: 2
us-east: 3

Approach

For each region, read its count (default 0), add 1, and store it back. Then loop over the keys to print.

  • Python: counts[region] = counts.get(region, 0) + 1
  • Java: counts.put(region, counts.getOrDefault(region, 0) + 1)
  • C++: counts[region]++. For a number value, [] starts a missing key at 0 automatically, so ++ just works. (Earlier, [] adding a missing key was a trap. Here it is exactly what you want.)

Note on order: Python and Java's LinkedHashMap print keys in the order they were first added. C++'s std::map prints keys sorted alphabetically. The regions here first appear in alphabetical order, so all three print the same thing.

DSA connection: counting values with a hash map is the classic frequency-counting pattern.

regions = ["ap-south", "eu-west", "us-east", "eu-west", "us-east", "us-east"]
counts = {}
for region in regions:
    counts[region] = counts.get(region, 0) + 1
for region in counts:
    print(f"{region}: {counts[region]}")