Max Chrétien Max Chrétien - 8 months ago 26
Python Question

Get first letter with maximum occurence of a string

I would like to get the first letter with the maximum occurence of a string.

For instance:

"google" -> g
"azerty" -> a
"bbbaaa" -> b

I already have a working code, using OrdererDict() to avoid automatic keys rearangement:

from collections import OrderedDict

sentence = "google"

d = OrderedDict()

for letter in sentence:
if letter not in d.keys():
d[letter] = sentence.count(letter)

print(max(d, key=d.get)) # g

but I'm looking for a possible one-liner or more elegant solution (if it's possible).

I already tried to use Counter() but it doesn't work, since dict in python don't remember the order that keys were inserted.


from collections import Counter

sentence = "bbbaaa"

c = Counter(sentence)
print(c.most_common()[0][0]) # have 50% chances of printing 'a' rather than 'b'.

Bonus question: Can someone explains why OrderedDict() are not the default dictionary behavior in python?


The documentation for collections.OrderedDict actually has a recipe for an OrderedCounter:

In [5]: from collections import Counter, OrderedDict

In [6]: class OrderedCounter(Counter, OrderedDict):
   ...:     pass

In [7]: OrderedCounter("google").most_common()[0][0]
Out[7]: 'g'