DSA Counting with Frequency Maps
A frequency map is a dict that stores each distinct value beside its count. One pass over the data builds the whole table.
Count the values
Each value in the list raises its own count. Sorted keys keep the print order stable.
counts = {}
for item in ["red", "blue", "red", "green", "blue", "red"]:
counts[item] = counts.get(item, 0) + 1
for key in sorted(counts):
print(key, counts[key])Read a count safely
The get method answers zero for a value never seen. The table stays unchanged.
counts = {"red": 3, "blue": 2}
print(counts.get("red", 0))
print(counts.get("yellow", 0))Find the largest count
The max function can compare values by their counts. The winning key is the answer.
counts = {"Ana": 4, "Ben": 7, "Cid": 5}
top = max(counts, key=counts.get)
print(top, counts[top])Example
votes = ["Mia", "Leo", "Mia", "Ana", "Mia", "Leo", "Mia", "Ana", "Mia"]
counts = {}
for name in votes:
counts[name] = counts.get(name, 0) + 1
for name in sorted(counts):
print(name, counts[name])
best = max(counts, key=counts.get)
print("total votes:", len(votes))
print("majority:", best, counts[best])
print("more than half:", counts[best] * 2 > len(votes))Key points
- A frequency map stores each distinct value beside its count.
- The pattern count.get(value, 0) + 1 adds one to a count.
- A missing value starts at zero through the default.
- The largest count in the table names the most frequent value.
- Many counting questions become simple table lookups after one pass.
In this example, the loop counts every vote into the frequency table. The sorted print shows Mia with five votes. Five doubled beats nine total votes. So Mia holds more than half the votes. A faster voting shortcut for this job comes in the Intermediate course.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Python Playground
Exercise
A list holds 12 items and one value appears 7 times. What is true?