pythonstringdictionary

Find the most occurring character in a string


This piece of code is going to find the most occurring chr in a string ,and it almost works fine through a dictionary ,but unfortunately the problem is that I want to make it return the last key when there are two keys with the same frequency ,but it returns the first one.

And this is what I have done so far:

def most_frequent_letter(s):
    st = s.lower().replace(' ', '')
    frequencies = {}
    for items in st:
        if items in frequencies:
            frequencies[items] += 1
        else:
            frequencies[items] = 1

    return max(frequencies, key=frequencies.get)




most_frequent_letter('mmmaaa')
Out[48]: 'm'

However I don't know how to return 'a' instead of 'm'.


Solution

  • Here's a way that creates a reverse frequency dictionary. I also made the creation of the frequency dictionary and its reverse fairly succinct by using a dictionary comprehension:

    def most_frequent_letter(s):
        st = s.lower().replace(' ', '')
        frequencies = {}
        frequencies = {item: frequencies.setdefault(item, 0) + 1 for item in st}
        rev_freq = {count: key for key, count in frequencies.items()}
        return rev_freq[max(rev_freq)]
    
    print(most_frequent_letter('nnmmmaaa'))  # -> a