collections.Counter already does what you want.

Copyfrom collections import Counter
c = Counter([1,2,3,4,5,100,100,1000])
print(c)
# Counter({100: 2, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 1000: 1})
Answer from tzaman on Stack Overflow
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ counting-the-frequencies-in-a-list-using-dictionary-in-python
Counting the Frequencies in a List Using Dictionary in Python - GeeksforGeeks
October 25, 2025 - The Counter class from the collections module counts the frequency of each item in a list by creating a dictionary-like object where each unique item becomes a key and its count becomes the value.
Discussions

python - Counting word frequency and making a dictionary from it - Stack Overflow
I want to take every word from a text file, and count the word frequency in a dictionary. Example: 'this is the textfile, and it is used to take words and count' d = {'this': 1, 'is': 2, 'the': ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Creating a dictionary of tokens with frequency
A dictionary holds key, value pairs. In this case, the keys are the tokens, example = {'a': 4, 'b': 3, ...} We reference an entry in the dictionary using a key, example['a']. t is a variable that references a str object which will be each token in turn. If the key does not already exist in the dictionary, we create a new entry for that key and assign a value of 1, otherwise we retrieve the current value and add 1. More on reddit.com
๐ŸŒ r/learnpython
3
2
October 31, 2021
python - Best way to turn word list into frequency dict - Stack Overflow
What's the best way to convert a list/tuple into a dict where the keys are the distinct values of the list and the values are the the frequencies of those distinct values? In other words: ['a', '... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Using a dictionary to find letter frequency from a list of words
Once you have a word, you can iterate over single characters of that word: a = 'python' for char in a: print(ch) So just do for each character what you do for each word. More on reddit.com
๐ŸŒ r/learnpython
6
1
September 25, 2019
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-frequencies-of-values-in-a-dictionary
Python - Frequencies of Values in a Dictionary - GeeksforGeeks
April 25, 2023 - # Python3 code to demonstrate working of # Dictionary Values Frequency # Using defaultdict() + loop from collections import defaultdict # initializing dictionary test_dict = {'ide' : 3, 'Gfg' : 3, 'code' : 2} # printing original dictionary print("The original dictionary : " + str(test_dict)) # Dictionary Values Frequency # Using defaultdict() + loop res = defaultdict(int) for key, val in test_dict.items(): res[val] += 1 # printing result print("The frequency dictionary : " + str(dict(res)))
๐ŸŒ
w3resource
w3resource.com โ€บ python-exercises โ€บ dictionary โ€บ python-data-type-dictionary-exercise-61.php
Python: Count the frequency in a given dictionary - w3resource
June 28, 2025 - Write a Python program to iterate over dictionary values and build a new dictionary mapping each value to its occurrence count.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ counting-the-frequencies-in-a-list-using-dictionary-in-python
Counting the frequencies in a list using dictionary in Python
August 23, 2019 - list = ['a','b','a','c','d','c','c'] frequency = {} for item in list: frequency[item] = list.count(item) for key, value in frequency.items(): print("% s -> % d" % (key, value))
๐ŸŒ
YouTube
youtube.com โ€บ watch
Counting the frequencies in a list using dictionary | Python | Castor Classes - YouTube
Code:num1=[1,1,2,3,2,5,7,5];dict1={};for num in num1: if num in dict1: dict1[num]=dict1[num]+1; else: dict1[num]=1;Python for beginners:h
Published ย  May 18, 2020
Top answer
1 of 13
16

If you don't want to use collections.Counter, you can write your own function:

import sys

filename = sys.argv[1]
fp = open(filename)
data = fp.read()
words = data.split()
fp.close()

unwanted_chars = ".,-_ (and so on)"
wordfreq = {}
for raw_word in words:
    word = raw_word.strip(unwanted_chars)
    if word not in wordfreq:
        wordfreq[word] = 0 
    wordfreq[word] += 1

for finer things, look at regular expressions.

2 of 13
14

Although using Counter from the collections library as suggested by @Michael is a better approach, I am adding this answer just to improve your code. (I believe this will be a good answer for a new Python learner.)

From the comment in your code it seems like you want to improve your code. And I think you are able to read the file content in words (while usually I avoid using read() function and use for line in file_descriptor: kind of code).

As words is a string, in for loop, for i in words: the loop-variable i is not a word but a char. You are iterating over chars in the string instead of iterating over words in the string words. To understand this, notice following code snippet:

>>> for i in "Hi, h r u?":
...  print i
... 
H
i
,
 
h
 
r
 
u
?
>>> 

Because iterating over the given string char by chars instead of word by words is not what you wanted to achieve, to iterate words by words you should use the split method/function from string class in Python.
str.split(str="", num=string.count(str)) method returns a list of all the words in the string, using str as the separator (splits on all whitespace if left unspecified), optionally limiting the number of splits to num.

Notice the code examples below:

Split:

>>> "Hi, how are you?".split()
['Hi,', 'how', 'are', 'you?']

loop with split:

>>> for i in "Hi, how are you?".split():
...  print i
... 
Hi,
how
are
you?

And it looks like something you need. Except for word Hi, because split(), by default, splits by whitespaces so Hi, is kept as a single string (and obviously) you don't want that.

To count the frequency of words in the file, one good solution is to use regex. But first, to keep the answer simple I will be using replace() method. The method str.replace(old, new[, max]) returns a copy of the string in which the occurrences of old have been replaced with new, optionally restricting the number of replacements to max.

Now check code example below to see what I suggested:

>>> "Hi, how are you?".split()
['Hi,', 'how', 'are', 'you?'] # it has , with Hi
>>> "Hi, how are you?".replace(',', ' ').split()
['Hi', 'how', 'are', 'you?'] # , replaced by space then split

loop:

>>> for word in "Hi, how are you?".replace(',', ' ').split():
...  print word
... 
Hi
how
are
you?

Now, how to count frequency:

One way is use Counter as @Michael suggested, but to use your approach in which you want to start from empty an dict. Do something like this code sample below:

words = f.read()
wordfreq = {}
for word in .replace(', ',' ').split():
    wordfreq[word] = wordfreq.setdefault(word, 0) + 1
    #                ^^ add 1 to 0 or old value from dict 

What am I doing? Because initially wordfreq is empty you can't assign it to wordfreq[word] for the first time (it will raise key exception error). So I used setdefault dict method.

dict.setdefault(key, default=None) is similar to get(), but will set dict[key]=default if key is not already in dict. So for the first time when a new word comes, I set it with 0 in dict using setdefault then add 1 and assign to the same dict.

I have written an equivalent code using with open instead of single open.

with open('~/Desktop/file') as f:
    words = f.read()
    wordfreq = {}
    for word in words.replace(',', ' ').split():
        wordfreq[word] = wordfreq.setdefault(word, 0) + 1
print wordfreq

That runs like this:

$ cat file  # file is 
this is the textfile, and it is used to take words and count
$ python work.py  # indented manually 
{'and': 2, 'count': 1, 'used': 1, 'this': 1, 'is': 2, 
 'it': 1, 'to': 1, 'take': 1, 'words': 1, 
 'the': 1, 'textfile': 1}

Using re.split(pattern, string, maxsplit=0, flags=0)

Just change the for loop: for i in re.split(r"[,\s]+", words):, that should produce the correct output.

Edit: better to find all alphanumeric character because you may have more than one punctuation symbols.

>>> re.findall(r'[\w]+', words) # manually indent output  
['this', 'is', 'the', 'textfile', 'and', 
  'it', 'is', 'used', 'to', 'take', 'words', 'and', 'count']

use for loop as: for word in re.findall(r'[\w]+', words):

How would I write code without using read():

File is:

$ cat file
This is the text file, and it is used to take words and count. And multiple
Lines can be present in this file.
It is also possible that Same words repeated in with capital letters.

Code is:

$ cat work.py
import re
wordfreq = {}
with open('file') as f:
    for line in f:
        for word in re.findall(r'[\w]+', line.lower()):
            wordfreq[word] = wordfreq.setdefault(word, 0) + 1
  
print wordfreq

Used lower() to convert an upper letter to lower letter.

output:

$python work.py  # manually strip output  
{'and': 3, 'letters': 1, 'text': 1, 'is': 3, 
 'it': 2, 'file': 2, 'in': 2, 'also': 1, 'same': 1, 
 'to': 1, 'take': 1, 'capital': 1, 'be': 1, 'used': 1, 
 'multiple': 1, 'that': 1, 'possible': 1, 'repeated': 1, 
 'words': 2, 'with': 1, 'present': 1, 'count': 1, 'this': 2, 
 'lines': 1, 'can': 1, 'the': 1}
Find elsewhere
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ creating a dictionary of tokens with frequency
r/learnpython on Reddit: Creating a dictionary of tokens with frequency
October 31, 2021 -

Hi, in my class we recently learned how to make a dictionary that takes the tokens of a text file as keys and the frequency of those tokens as values. The code does work but I'm having a hard time understanding HOW it works.

This is the code (inside a function) I have:

token_list = [i for i in token if i[0] in vowels]
    d = {}
    for t in token_list:
        if t in d:
            d[t] += 1
        else:
            d[t] = 1
    return d

token_list is all the tokens in Alice in Wonderland that start with vowel. What I don't understand is what d[t] is. I suppose it's the values since it increases at each iteration, but why is it written like this? And from where does the dictionary take the keys? if t in d is especially confusing to me, because since d is empty at the beginning, how can the if actually work?

Thank you for anyone that can answer my questions and maybe break down this code for me!

๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ counting-word-frequency-and-making-a-dictionary-from-it
Counting Word Frequency and Making a Dictionary from it - GeeksforGeeks
July 23, 2025 - This method uses dictionary comprehension to build a frequency dictionary by iterating over the unique words in the input string. It is concise but less efficient due to repeated calls to the count() method for each unique word. ... a = "Python with Python gfg with Python" # Counting frequency using dictionary comprehension b = {c: a.split().count(c) for c in set(a.split())} print(b)
๐ŸŒ
Python-Fiddle
python-fiddle.com โ€บ challenges โ€บ element-frequency-dictionary
Element Frequency Dictionary - Python Challenge
... Code is executed with Pyodide, a port of CPython to WebAssembly/Emscripten. Some functionality in Python may not be available or may not work as expected. ... from typing import List, Dict def freq_count(elements: List) -> Dict: """ Calculate the frequency of each element in the input list.
๐ŸŒ
Programming Historian
programminghistorian.org โ€บ en โ€บ lessons โ€บ counting-frequencies
Counting Word Frequencies with Python | Programming Historian
July 17, 2012 - Building on what we have so far, we want a function that can convert a list of words into a dictionary of word-frequency pairs. The only new command that we will need is dict, which makes a dictionary from a list of pairs.
๐ŸŒ
YouTube
youtube.com โ€บ watch
Write a Python Program to Count the Frequencies in a List Using Dictionary - YouTube
Hi, in this video I tried to explain how you can Write a Python Program to Count the Frequencies in a List Using DictionaryPython Scripts ===================...
Published ย  August 21, 2022
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ python-program-to-count-the-frequency-of-words-appearing-in-a-string-using-a-dictionary
Python Program to Count the Frequency of Words Appearing in a String Using a Dictionary
my_string = input("Enter the string :") my_list=[] my_list=my_string.split() word_freq=[my_list.count(p) for p in my_list] print("The frequency of words is ...") print(dict(zip(my_list,word_freq)))
๐ŸŒ
CodinGeek
codingeek.com โ€บ home โ€บ python examples โ€บ how to count the frequencies in a list using a dictionary in python?
How to Count element frequencies using dictionary in Python?
March 7, 2023 - We can use this property to count the frequencies of elements in a list by treating each element in the list as a key in a dictionary and incrementing its value for each occurrence. Now letโ€™s implement a program to count the frequencies of the elements in Python.
๐ŸŒ
Medium
medium.com โ€บ @jeremiahlutes โ€บ frequency-tables-in-python-fcd53c0f8553
Frequency Tables in Python. An important skill in Data Science isโ€ฆ | by Jeremiah Lutes | Medium
February 24, 2020 - Frequency tables are dictionaries that are built from a dataset and build an easy to read occurrence of elements from the dataset. Since frequency tables in Python are dictionaries it is important to understand what ...
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ using a dictionary to find letter frequency from a list of words
r/learnpython on Reddit: Using a dictionary to find letter frequency from a list of words
September 25, 2019 -

Hi everyone,

I've been stuck on this assignment for a few hours. Essentially, I have to create a function that returns a dictionary. However, each key is a letter and the value is the count that represents how many times that letter was found. The letters have to be lowercase and I cannot use any modules or import anything. The code I have so far counts the frequency of words in a list, but I'm not sure how to break it down and have it count the letters.

Edit: I fixed the code so it now prints the letter frequency, but it's not exact. For example, there should be two g's but it only prints one. I'm not sure what the problem is. Can someone please help?

def build_letter_distribution(listOfWords):
  dictionary = {}
  for string in listOfWords:
    string = string.lower()
    for char in string:
        dictionary[char] = string.count(char)
  return dictionary
print(build_letter_distribution(["Penguin", "Dog", "cat", "CAT"]))

This is the output I get so far:

{'p': 1, 'e': 1, 'n': 2, 'g': 1, 'u': 1, 'i': 1, 'd': 1, 'o': 1, 'c': 1, 'a': 1, 't': 1}
๐ŸŒ
Data Science Dojo
discuss.datasciencedojo.com โ€บ python
How to use a Python dictionary for counting? - Python - Data Science Dojo Discussions
May 11, 2023 - Now, I need to count the frequency of words in the data. For instance, given this sample list: data_list = ['a', 'random', 'data', 'containing', 'random', 'words'] I want to count the frequency of occurrence of each word in this list. I read that Python dictionaries can be useful for this task.
๐ŸŒ
Studytonight
studytonight.com โ€บ python-programs โ€บ counting-the-frequencies-in-a-list-using-dictionary-in-python
Counting the frequencies in a list using dictionary in Python - Studytonight
In this tutorial, you will learn to write a program in Python that will count the frequency of elements in a list using a dictionary. For a given list with multiple elements, we have to count the occurrence of each element in the list and display it as output.