'Printing the max key with the most common value

I need to find the most common number in string

string = '43534353545466'
d = {}
for i in set(string):
    d[i] = string.count(i)

print(max(d, key=d.get), max(d.values()))

But i have problem with the second task: If there are a few numbers that occurs the same amount of times, i need to print the biggest one(In this example: '5:4'). What's the easiest way to do this?



Solution 1:[1]

This is practically the same as Sorting a dictionary by value then by key, just using max instead of sorting.

>>> max(d.items(), key=lambda item: (item[1], item[0]))
('5', 4)

Solution 2:[2]

Use collections.Counter

from collections import Counter
c = Counter(string)
most = c.most_common(1)[0][1]
max((i for i in c.most_common() if i[1] == most), key=lambda x: x[0])
('5', 4)

Solution 3:[3]

If you prefer not to import any modules (not that you shouldn't) you could do this:

string = '43534353545466'

d = {k:string.count(k) for k in set(string)}

c, n = sorted((v, k) for k, v in d.items())[-1]

print(f'Digit {n} occurs {c} times')

Output:

Digit 5 occurs 4 times

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 wjandrea
Solution 2 Klas Å .
Solution 3