Skip to content Skip to sidebar Skip to footer

Dictionary: How To Find Max Of Elements

Given a dictionary of... result={'A - - -': ['ALLY'], '- - A -': ['DEAL'], '- - - A': ['BETA'], '- - - -': ['COOL', 'ELSE', 'FLEW', 'GOOD', 'HOPE', 'IBEX']} How would I go abou

Solution 1:

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.

Solution 2:

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]

Solution 3:

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?

Post a Comment for "Dictionary: How To Find Max Of Elements"