Reputation: 407
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?
Upvotes: 1
Views: 89
Reputation: 85442
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)]
Upvotes: 2
Reputation: 500317
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;Upvotes: 3
Reputation: 9670
>>> max_val = lambda xs: max(xs.iteritems(), key=lambda x: len(x[1]))
>>> max_val(fans)
('benfica', ['joao', 'ana', 'carla'])
Upvotes: 0