Maximum occurrences in a python dictionary

Asked

Viewed 479 times

3

If I have the dictionary:

meu_dic = {A:3, B:5, C:0, D:10, E:2}

resulting from:

meu_dic = {i:lista.count(i) for i in lista}

I know that To appears 3 times in the list, B 5 times, etc.. How can I return the maximum value of repetitions and the respective key? That is, for this dictionary I would have to return: 10, D.

3 answers

1

Do:

meu_dict = {'A':3, 'B':5, 'C':0, 'D':10, 'E':2}
max_value = sorted(meu_dict.items(), key=lambda tup: tup[1])[-1] # ('D', 10)

1

>>> max(map(tuple, map(reversed, Meu_dic.items())))
(10, 'D')

EDIT:

I thought of another way:

>>> max([i[::-1] for i in Meu_dic.items()])
(10, 'D')

0

As simple as possible:

key = max(dic, key=dic.get)
value = dic[key]
print key, value

dic is your dictionary.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.