Search code examples
pythondictionarymaxkey-value-store

discovering the biggest value in a dictionary


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?


Solution

  • 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).