Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get most frequent item in python dictionary given frequencies

How do I return the most commonly occurring element in a dictionary given the frequencies of each element? For example, in the following list, I want to return the most frequently occurring element by the first frequency and the most frequently occurring element by the second frequency?

dictionary = {"first": [30, 40], "second": [10, 30], "third": [20, 50] }

So the method findMostFreqFirst(dictionary) would return "first" and the method findMostFreqSecond would return "third." Is there a way I can do this using the most efficient amount of code possible? (I'm writing this as part of a much larger program so I don't want to write a copious amount of code for these two functions. Thanks!

like image 659
Quanquan Liu Avatar asked Mar 22 '23 23:03

Quanquan Liu


1 Answers

Use max with key keyword argument:

>>> dictionary = {"first": [30, 40], "second": [10, 30], "third": [20, 50] }
>>> max(dictionary, key=lambda key: dictionary[key][0])
'first'
>>> max(dictionary, key=lambda key: dictionary[key][1])
'third'

The first one can be written as follow because list comparison are done lexicographically. ([30, 40] > [20, 50])

>>> max(dictionary, key=dictionary.get)
'first'
like image 72
falsetru Avatar answered Apr 01 '23 01:04

falsetru