Finding the most frequent character in a string

There are many ways to do this shorter. For example, you can use the Counter class (in Python 2.7 or later):

import collections
s = "helloworld"
print(collections.Counter(s).most_common(1)[0])

If you don’t have that, you can do the tally manually (2.5 or later has defaultdict):

d = collections.defaultdict(int)
for c in s:
    d[c] += 1
print(sorted(d.items(), key=lambda x: x[1], reverse=True)[0])

Having said that, there’s nothing too terribly wrong with your implementation.

Leave a Comment