Python | Frequency of each character in String

Last Updated : 20 Apr, 2023

Given a string, the task is to find the frequencies of all the characters in that string and return a dictionary with key as the character and its value as its frequency in the given string.

Method #1 : Naive method Simply iterate through the string and form a key in dictionary of newly occurred element or if element is already occurred, increase its value by 1.

Python3

 `# Python3 code to demonstrate` `# each occurrence frequency using` `# naive method`   `# initializing string` `test_str ``=` `"GeeksforGeeks"`   `# using naive method to get count` `# of each element in string` `all_freq ``=` `{}`   `for` `i ``in` `test_str:` `    ``if` `i ``in` `all_freq:` `        ``all_freq[i] ``+``=` `1` `    ``else``:` `        ``all_freq[i] ``=` `1`   `# printing result` `print``(``"Count of all characters in GeeksforGeeks is :\n "` `      ``+` `str``(all_freq))`

Output

```Count of all characters in GeeksforGeeks is :
{'G': 2, 'e': 4, 'k': 2, 's': 2, 'f': 1, 'o': 1, 'r': 1}```

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #2: Using collections.Counter() The most suggested method that could be used to find all occurrences is this method, which actually gets all element frequencies and could also be used to print single element frequencies if required.

Python3

 `# Python3 code to demonstrate` `# each occurrence frequency using` `# collections.Counter()` `from` `collections ``import` `Counter`   `# initializing string` `test_str ``=` `"GeeksforGeeks"`   `# using collections.Counter() to get` `# count of each element in string` `res ``=` `Counter(test_str)`   `# printing result` `print``(``"Count of all characters in GeeksforGeeks is :\n "` `      ``+` `str``(res))`

Output

```Count of all characters in GeeksforGeeks is :
Counter({'e': 4, 'G': 2, 'k': 2, 's': 2, 'f': 1, 'o': 1, 'r': 1})```

Time Complexity: O(n)
Auxiliary Space:  O(n)

Method #3 : Using dict.get() get() method is used to check the previously occurring character in string, if its new, it assigns 0 as initial and appends 1 to it, else appends 1 to previously holded value of that element in dictionary.

Python3

 `# Python3 code to demonstrate` `# each occurrence frequency using` `# dict.get()`   `# initializing string` `test_str ``=` `"GeeksforGeeks"`   `# using dict.get() to get count` `# of each element in string` `res ``=` `{}`   `for` `keys ``in` `test_str:` `    ``res[keys] ``=` `res.get(keys, ``0``) ``+` `1`   `# printing result` `print``(``"Count of all characters in GeeksforGeeks is : \n"` `      ``+` `str``(res))`

Output

```Count of all characters in GeeksforGeeks is :
{'G': 2, 'e': 4, 'k': 2, 's': 2, 'f': 1, 'o': 1, 'r': 1}```

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #4: Using set() + count() count() coupled with set() can also achieve this task, in this we just iterate over the set converted string and get the count of each character in original string and assign that element with that value counted using count().

Python3

 `# Python3 code to demonstrate` `# each occurrence frequency using` `# set() + count()`   `# initializing string` `test_str ``=` `"GeeksforGeeks"`   `# using set() + count() to get count` `# of each element in string` `res ``=` `{i: test_str.count(i) ``for` `i ``in` `set``(test_str)}`   `# printing result` `print``(``"The count of all characters in GeeksforGeeks is :\n "` `      ``+` `str``(res))`

Output

```The count of all characters in GeeksforGeeks is :
{'k': 2, 'f': 1, 'o': 1, 'e': 4, 'G': 2, 's': 2, 'r': 1}```

Time Complexity: O(n)
Auxiliary Space:  O(n)

Method #5: Using set() + operator.countOf() operator.countOf() coupled with set() can also achieve this task, in this we just iterate over the set converted string and get the count of each character in original string and assign that element with that value counted using operator.countOf().

Python3

 `# Python3 code to demonstrate` `# each occurrence frequency using` `# set() + operator.countOf()` `import` `operator as op` `# initializing string` `test_str ``=` `"GeeksforGeeks"`   `# using set() + operator.countOf() to get count` `# of each element in string` `res ``=` `{i: op.countOf(test_str,i) ``for` `i ``in` `set``(test_str)}`   `# printing result` `print``(``"The count of all characters in GeeksforGeeks is :\n "` `      ``+` `str``(res))`

Output

```The count of all characters in GeeksforGeeks is :
{'r': 1, 'o': 1, 's': 2, 'G': 2, 'e': 4, 'k': 2, 'f': 1}```

Time Complexity: O(n)
Auxiliary Space:  O(n)

Method #6:Using reduce

1. Take input string from user
2. Initialize an empty dictionary all_freq to store the frequency of each character
3. Loop through each character i in the string
a. Check if i is already a key in all_freq dictionary
i. If yes, increment its value by 1
ii. If no, add i as a new key to all_freq dictionary and set its value to 1
4. Print the final all_freq dictionary.

Python3

 `from` `functools ``import` `reduce`   `# initializing string` `test_str ``=` `"GeeksforGeeks"`   `# using reduce to get count of each element in string` `all_freq ``=` `dict``(``reduce``(``lambda` `x, y: {``*``*``x, y: x.get(y, ``0``) ``+` `1``}, test_str, {}))`   `# printing result` `print``(``"Count of all characters in GeeksforGeeks is :\n "` `+` `str``(all_freq))` `#This code is contributed by Vinay Pinjala.`

Output

```Count of all characters in GeeksforGeeks is :
{'G': 2, 'e': 4, 'k': 2, 's': 2, 'f': 1, 'o': 1, 'r': 1}```

Time complexity: O(n), where n is the length of the input string. This is because the algorithm iterates through each character in the string exactly once, and performs a constant amount of work (checking if the character is in the dictionary and incrementing its count, or adding it to the dictionary with a count of 1).
Auxiliary space: O(k), where k is the number of unique characters in the input string. This is because the algorithm uses a dictionary to store the count of each character in the string. The size of the dictionary is equal to the number of unique characters in the string. In the worst case, when all characters in the input string are unique, the space complexity would be O(n).

Method #7: Using  numpy:

Step-by-step approach:

• Convert the input string into a list of characters using the list() method.
• Use numpy’s unique() method to find the unique characters in the list and their counts.
• Use the zip() method to combine the unique characters and their counts into a dictionary.
• Print the resulting dictionary.

Below is the implementation of the above approach:

Python3

 `import` `numpy as np`   `# initializing string` `test_str ``=` `"GeeksforGeeks"`   `# using numpy to get count of each element in string` `unique, counts ``=` `np.unique(np.array(``list``(test_str)), return_counts``=``True``)` `all_freq ``=` `dict``(``zip``(unique, counts))`   `# printing result` `print``(``"Count of all characters in GeeksforGeeks is :\n "` `+` `str``(all_freq))` `#This code is contributed by Jyothi pinjala`

Output:

```Count of all characters in GeeksforGeeks is :
{'G': 2, 'e': 4, 'f': 1, 'k': 2, 'o': 1, 'r': 1, 's': 2}```

Time Complexity: O(n), where n is the length of the input string. The unique() method takes O(n) time complexity, and the zip() method takes constant time
Auxiliary Space: O(k), where k is the number of unique characters in the input string. The space required to store the resulting dictionary is proportional to the number of unique characters.