Find Frequency of Characters in Python (original) (raw)
Last Updated : 14 Nov, 2024
In this article, we will explore various methods to count the frequency of characters in a given string. One simple method to count frequency of each character is by using a dictionary.
Using Dictionary
The idea is to traverse through each character in the string and keep a count of how many times it appears.
Python `
s = "GeeksforGeeks" freq = {}
for c in s: if c in freq: freq[c] += 1 else: freq[c] = 1
print(freq)
`
Output
{'G': 2, 'e': 4, 'k': 2, 's': 2, 'f': 1, 'o': 1, 'r': 1}
**Explanation: We use a dictionary **freq to store each character as the **key and its count as the **value. We loop through the string **s and check if the character is already in the dictionary. If it is then increase its count by 1. Otherwise, set its frequency to 1.
**Let's explore other various methods to find the frequency of each character in String:
Table of Content
Using Counter from collections Library
The **collections module has a built-in Counterclass to count character frequencies in a string.
Python `
from collections import Counter
s = "GeeksforGeeks"
Count character frequency using Counter
freq = Counter(s)
print(dict(freq))
`
Output
{'G': 2, 'e': 4, 'k': 2, 's': 2, 'f': 1, 'o': 1, 'r': 1}
**Explanation: **Counter(s) counts the frequency of each character in **s and returns a **Counter object which is a dictionary-like collection. To convert back to dictionary we can wrap the **freq with **dict()
Using Dictionary Comprehension
A dictionary comprehension can also be used to count character frequencies in a concise form.
Python `
s = "GeeksforGeeks"
Count characters using dictionary comprehension
freq = {c: s.count(c) for c in s}
print(freq)
`
Output
{'G': 2, 'e': 4, 'k': 2, 's': 2, 'f': 1, 'o': 1, 'r': 1}
**Explanation: {char: s.count(char) for char in s} creates a dictionary where each character in s is a key and **s.count(c) gives its frequency.