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!
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With