Five Ways to Count Characters in a String in Python
If you wanted to count the number of characters in a string in Python or otherwise convert a list to a dictionary with each item counted, there are a variety of ways to do it.
1. Import Counter
Python has a module called Counter which does exactly this. It creates a Counter object which can be converted into a dictionary simply by wrapping it in dict()
.
This works on my nonsense string of “BcRmmBcmRccc”, but this method and others in this post will also work on any list:
Maybe this solution is too simple. Someone on StackOverflow complained, “Yuck. Enough narrow-purpose bloat in the Python library, already.” Someone else countered that this task is common enough that it merits its own module.
In any case, Python has many ways to fulfill this task without having to import a specialized module. Learning how to use other methods helps understanding how lists and dictionaries work.
2. Loop through the string
Here, an empty dictionary is instantiated. Then, do a for
loop through the string . If the key is not yet in the dictionary, create it with a value of 1, and if it is, add 1 to the key’s value.
3. Short version using count()
This version does a one-line for
loop. It uses the count()
method, which is distinct from the name of my function, and adds the number to a dictionary key. What count does is simply counts the number of items in a list.
Here’s a simple example:
And here’s how it would be incorporated into my function.
4. Use get()
Supply a dictionary and a key to Python’s get()
method, and it will return the key’s value.
Here’s how to apply this method to the count function at hand:
Create an empty dictionary, and loop through the list like before. The 0 in counted.get(i, 0)
instructs Python to set it as a default value if the key doesn’t yet exist, and then the function is adding 1 to it.
5. Use setdefault()
In this situation, setdefault()
does exactly the same thing as get()
. It creates the key if it doesn’t exist with a default value of 0 and then adds 1. If it does exist, it adds 1 again.
So there are five methods to convert a string or a list into a dictionary with each value counted. And that’s just the beginning. There are even more.