discovering the biggest value in a dictionary

87 views Asked by At

I'm trying to figure out the biggest value within a dictionary, and I'm having some trouble with this. Here's my code:

def most_fans(dictionary):
    empty = ''
    for key in dictionary:
        if len(dictionary[key]) > next(dictionary[key]):
            empty = key
    print(empty)

I realize the problem with my code, since if I have a dictionary such as this:

fans={'benfica': ['joao','ana','carla'],
      'sporting': ['hugo','patricia'],
      'porto': ['jose']}

The output will be both 'benfica' and 'sporting'.Because benfica is bigger then sporting but sporting is also bigger then porto. And yet this the best I came up with.

Can someone show me a decent way to do this?

3

There are 3 answers

0
NPE On BEST ANSWER

You could just use max() with a key:

>>> max(fans, key=lambda team:len(fans[team]))
'benfica'

Here:

  • max(fans, ...) iterates over the keys of fans (that is, team names) looking for the largest element according to some criterion;
  • the lambda function specifies that criterion (in this example, the number of fans the team has).
0
Meitham On
>>> max_val = lambda xs: max(xs.iteritems(), key=lambda x: len(x[1]))
>>> max_val(fans)
('benfica', ['joao', 'ana', 'carla'])
1
Mike Müller On

If you have two teams with same number of fans:

fans = {'benfica':['joao','ana','carla'],
        'sporting':['hugo','patricia', 'max'],
        'porto':['jose']}

The max()approach gives you only one of them:

>>> max(fans, key=lambda team:len(fans[team]))
'benfica'

Using collections.Counter, you can get the most common ones:

>>> from collections import Counter
>>> counts = Counter({k: len(v) for k, v in fans.items()})
>>> counts.most_common(2)
[('benfica', 3), ('sporting', 3)]

or all:

>>> counts.most_common()
[('benfica', 3), ('sporting', 3), ('porto', 1)]