Find max occurrences in python string

Hi Friend,

This is very easy few lines of code in python to find maximum occurrences of characters in string. I hope that no need to explain more about the code here. It clearly tells you the function.

a = 'dsffsdfgsdfgasgdfbvngjdfjgdfghsdfhsgfdjyjmndsgsedrgyergbafdsgbhdfsgdsfg'
temp_dict = {}
for val in a:
        temp_dict[val] += 1
    except KeyError:
        temp_dict[val] = 1

sorted_dict = sorted(temp_dict.items(), key=lambda x: x[1], reverse=True)
print sorted_dict[:5]


[('d', 32), ('g', 32), ('f', 32), ('s', 18), ('h', 16)]

Django-Python Web based application developer.

Share This Post

Related Articles

Leave a Reply

© 2018 Techy Diary. All rights reserved.
Powered by Charvi Groups