Count Occurrences in Python Dictionary

I have found that counting data is one of the most frequent tasks I perform. Whether I am analyzing demographic trends in California or tracking inventory for a New York retail chain, I always rely on Python dictionaries.

Python dictionaries are incredibly efficient for storing key-value pairs, making them the perfect tool for frequency counting.

In this tutorial, I will show you exactly how to handle a Python dictionary count using various professional techniques.

The Need for Python Dictionary Counting

When you work with large datasets, such as a list of US states or a collection of American car brands, you often need to know how many times an item appears. A Python dictionary allows you to map a specific item (the key) to its frequency (the value).

I remember early in my career, I used to write long, messy loops to handle this, but Python offers much cleaner ways to do it now.

Let’s look at the different methods you can use to master the Python dictionary count process.

Method 1: Use a Simple Python For Loop

The most fundamental way to perform a Python dictionary count is by using a standard for loop.

I still use this method occasionally when I want full control over the logic without importing extra libraries.

# List of US Tech Hubs
tech_hubs = ["San Francisco", "Austin", "Seattle", "San Francisco", "Austin", "New York", "San Francisco"]

# Initialize an empty Python dictionary
hub_count = {}

# Iterate through the list to perform Python dictionary count
for hub in tech_hubs:
    if hub in hub_count:
        hub_count[hub] += 1
    else:
        hub_count[hub] = 1

print(hub_count)

You can refer to the screenshot below to see the output.

python dictionary count values per key

In this Python code, I check if the city already exists as a key in my Python dictionary. If it exists, I increment the value; if it doesn’t, I initialize it to one.

Method 2: Use the Python Dictionary get() Method

A slightly more elegant way to handle a Python dictionary count is by using the .get() method.

The .get() method is great because it prevents the “KeyError” that occurs when you try to access a key that isn’t there yet.

# List of popular American car brands
cars = ["Ford", "Tesla", "Chevrolet", "Tesla", "Ford", "Ford", "Dodge"]

car_count = {}

for car in cars:
    # Use get to provide a default value of 0 if key is missing
    car_count[car] = car_count.get(car, 0) + 1

print(car_count)

You can refer to the screenshot below to see the output.

python dictionary count

By using .get(car, 0), I am telling Python to return 0 if the car brand isn’t in the dictionary yet. This simplifies the Python dictionary count logic into a single line inside the loop.

Method 3: Use Python collections.Counter (The Pro Way)

If you ask me which method is my favorite, it is definitely the Counter class from the collections module.

In my experience, this is the most “Pythonic” way to perform a Python dictionary count. It is highly optimized and requires the least amount of code.

from collections import Counter

# List of US Ivy League Universities
universities = ["Harvard", "Yale", "Princeton", "Harvard", "Yale", "Harvard", "Columbia"]

# Perform Python dictionary count using Counter
uni_counts = Counter(universities)

# Convert to a standard Python dictionary if needed
uni_dict = dict(uni_counts)

print(uni_dict)

You can refer to the screenshot below to see the output.

count dictionary python

The Counter object essentially acts as a Python dictionary specifically designed for counting. It is incredibly fast, especially when dealing with massive lists of data like US Zip Codes.

Method 4: Use Python collections.defaultdict

Another tool I use frequently is defaultdict. It is very helpful when you are building a complex Python dictionary count system.

Unlike a regular Python dictionary, defaultdict automatically assigns a default value to a new key.

from collections import defaultdict

# List of professional US sports leagues
leagues = ["NFL", "NBA", "MLB", "NFL", "NHL", "NBA", "NFL"]

# Initialize defaultdict with int (which defaults to 0)
league_counts = defaultdict(int)

for league in leagues:
    league_counts[league] += 1

print(dict(league_counts))

You can refer to the screenshot below to see the output.

dictionary count

I prefer defaultdict when I am doing more than just counting, such as grouping American cities by state.

Method 5: Python Dictionary Count with Dictionary Comprehension

If you already have a set of unique items, you can use a Python dictionary comprehension. I usually use this when I have a unique list of U.S. presidents and want to count their mentions in a text.

# Mentions of US Presidents in a document
mentions = ["Lincoln", "Washington", "Lincoln", "Jefferson", "Washington", "Lincoln"]

# Use set() to get unique names and then count in a Python dictionary
presidents_count = {name: mentions.count(name) for name in set(mentions)}

print(presidents_count)

This Python code is very readable and fits onto a single line.

Method 6: Count Characters in a String using Python Dictionary

Sometimes the data isn’t a list; it’s a string. Suppose you want to count the frequency of each character in a string like “United States of America”.

You can apply the same Python dictionary count logic here.

# Target string
country_name = "United States of America"

# Remove spaces for a cleaner Python dictionary count
country_name = country_name.replace(" ", "")

char_count = Counter(country_name)

print(dict(char_count))

I find this particularly useful when I am cleaning data for American marketing campaigns.

Method 7: Use the Python count() Method for Specific Keys

If you only care about one or two specific items, you don’t need a full Python dictionary count.

For example, if you only want to know how many times “Texas” appears in a list of US states.

states = ["Texas", "Florida", "California", "Texas", "New York", "Texas"]

# Simple count for a specific item
texas_count = states.count("Texas")

print(f"Texas appears {texas_count} times.")

While this doesn’t return a Python dictionary, it is the fastest way to find a single value.

Common Issues in Python Dictionary Counting

In my years of coding, I have seen many developers struggle with KeyError issues. Always remember that a Python dictionary will throw an error if you try to increment a key that doesn’t exist.

Using Counter or the .get() method is the best way to avoid this frustration. Another tip: if you are working with case-sensitive data (like “USA” vs “usa”), make sure to normalize your strings.

I always convert my strings to lowercase before starting a Python dictionary count.

Handle Large Datasets in the USA

If you are dealing with millions of records, like every flight landing at JFK airport, efficiency matters. In those cases, I highly recommend using the Counter method.

It is written in C under the hood, making it significantly faster than a manual Python for loop. I hope this guide has been helpful for your Python journey.

Knowing how to efficiently perform a Python dictionary count is a skill you will use almost every day.

In this tutorial, I have covered several ways you can perform a Python dictionary count. I have also shown you how to use the Counter class and the get() method to make your code more robust.

If you’re working with data analysis or just organizing information, these methods will save you a lot of time. I’ve found that using the right method for the right task makes a huge difference in my daily work.

You may also read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.