Reputation: 1396
Given a dictionary of...
result={'A - - -': ['ALLY'], '- - A -': ['DEAL'], '- - - A': ['BETA'], '- - - -': ['COOL', 'ELSE', 'FLEW', 'GOOD', 'HOPE', 'IBEX']}
How would I go about assigning a variable 'Answer' to the key with the most elements? I tried...
inverse=[(value,key) for key, value in result.items()]
Answer=max(inverse)
but that got me no where. Since the largest family is ['COOL', 'ELSE', 'FLEW', 'GOOD', 'HOPE', 'IBEX'] I would like to be able to assign '- - - -' to 'Answer'.
Upvotes: 0
Views: 120
Reputation: 23480
import operator
dict(sorted(result.iteritems(), key=operator.itemgetter(1), reverse=True)[:1])
There you have your maximum value, now just assign something to it?
Upvotes: -2
Reputation: 88977
max()
takes a key
keyword argument which allows you to give a sorting function:
>>> answer, _ = max(result.items(), key=lambda x: len(x[1]))
>>> answer
'- - - -'
This will be more efficient than constructing an extra list just to sort on.
Upvotes: 4
Reputation: 62898
You are sorting by the lists themselves instead of their length:
inverse = [(len(value), key) for key, value in result.items()]
Answer = max(inverse)[1]
Upvotes: -1