Bob
Bob

Reputation: 1396

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 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

Answers (3)

Torxed
Torxed

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

Gareth Latty
Gareth Latty

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

Pavel Anossov
Pavel Anossov

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

Related Questions