October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk2 min

How to Count Occurrences in a Python Dictionary

Use collections.Counter(my_dict.values()) to count how often each value appears in a Python dictionary. Learn when defaultdict is useful and how missing keys behave.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To count how often each value appears in a Python dictionary, pass its values view to collections.Counter: Counter(my_dict.values()). To count items from any iterable, use Counter(iterable). Both approaches require hashable items.

Count repeated values in a dictionary

A dictionary maps keys to values; it does not automatically track how often a value occurs. Use Counter from the standard library to build a frequency map of the values:

from collections import Counter

inventory = {
    "first": "apple",
    "second": "banana",
    "third": "apple",
    "fourth": "orange",
    "fifth": "banana",
    "sixth": "apple",
}

counts = Counter(inventory.values())
print(counts)
# Counter({'apple': 3, 'banana': 2, 'orange': 1})

inventory.values() supplies the observations, so this counts repeated values—not the dictionary’s keys or its total number of entries. Counter is a dictionary subclass: its keys are the distinct values and its values are their counts. See the Python 3.14 Counter documentation.

Count items in a list or another iterable

For a list, tuple, or other iterable of hashable items, pass the iterable directly to Counter:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
from collections import Counter

items = ["apple", "banana", "apple", "orange", "banana", "apple"]
counts = Counter(items)

print(counts["apple"])  # 3

Because a Counter uses its items as dictionary keys, each item must be hashable. Strings, numbers, and tuples of hashable values are common examples; mutable lists and dictionaries are not valid counter items.

Use defaultdict when counting needs custom logic

If each item needs additional processing as it is counted, a defaultdict(int) provides a convenient loop. Its integer factory supplies zero when a missing key is first accessed with square brackets:

from collections import defaultdict

counts = defaultdict(int)
for item in items:
    counts[item] += 1

For a regular dictionary, counts[item] += 1 raises KeyError if item is not already a key. A defaultdict creates and stores a missing entry when accessed through counts[item]; calling counts.get(item) does not trigger its factory. The Python 3.14 defaultdict documentation describes this behavior.

Choose the right counting approach

Approach Best for Missing-key behavior
Counter(iterable) A concise tally or common frequency operations Reading an absent item returns 0.
defaultdict(int) A custom loop that does more than tally each item Indexed access creates and stores a zero-valued entry.
Plain dict When you deliberately manage key initialization yourself Reading an absent key with square brackets raises KeyError.

For most frequency counts, Counter is the clearest choice. Use defaultdict(int) when counting is one part of per-item logic. A plain dictionary also works if you initialize a key before incrementing it, but direct incrementing alone fails for an unseen key.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Get the most frequent items

Counter.most_common(n) returns up to n items as (item, count) pairs, ordered from highest count to lowest. For ties, items retain their first-encounter order:

counts = Counter(["apple", "banana", "apple", "banana", "orange"])
print(counts.most_common(2))
# [('apple', 2), ('banana', 2)]

Here, apple appears before banana in the input, so it appears first in the tied result. See the Python 3.14 most_common documentation.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Handle zero and negative counts

A counter can contain zero or negative values. Assigning zero does not remove an entry; delete the key explicitly if it should no longer be present:

counts["apple"] = 0
# "apple" remains a key in counts

del counts["apple"]
# "apple" is removed

This matters when inspecting the counter’s keys or converting it to another mapping: a zero-count entry remains present until deleted. The Counter documentation covers zero and negative counts.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.