Reputation: 1477
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!
Upvotes: 4
Views: 6065
Reputation: 142126
A bit late to the table, but an approach that can handle an arbitrary number of "columns" with varying lengths would be:
dictionary = {"first": [30, 40], "second": [10, 30], "third": [20, 50] }
from itertools import izip_longest
keys, vals = zip(*dictionary.items())
items = izip_longest(*vals, fillvalue=0)
print [keys[max(xrange(len(item)), key=item.__getitem__)] for item in items]
# ['first', 'third']
Upvotes: 0
Reputation: 103754
You can all at once this way.
First element:
>>> dictionary = {"first": [30, 40], "second": [10, 30], "third": [20, 50] }
>>> sorted(dictionary, key=lambda key: dictionary[key][0], reverse=True)
['first', 'third', 'second']
Then use an index to the sorted list to return the element in question:
>>> sorted(dictionary, key=lambda key: dictionary[key][0], reverse=True)[0]
'first'
Second element:
>>> sorted(dictionary, key=lambda key: dictionary[key][1], reverse=True)
['third', 'first', 'second']
If you want the second element to break a tie with the first:
>>> dictionary = {"first": [30, 40], "second": [10, 30], "third": [20, 50],
... "fourth":[30,60]}
>>> sorted(dictionary, key=lambda key: dictionary[key][0:2], reverse=True)
['fourth', 'first', 'third', 'second']
Upvotes: 0
Reputation: 368954
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'
Upvotes: 7