0

I am working on a dictionary that maps names to votes received. I need associate the name with the most votes, assigning it to the variable win.

So far:

vote = {}

for key in vote:
    vote(max(key)) = win

How do I associate win to the name, because I believe my error now is that I am associating it to the highest number.

Thank you for your help.

Oleksi
  • 12,802
  • 4
  • 55
  • 79
shme
  • 5
  • 1
  • 1
    This question is very unclear: for one thing, the code won't do anything since the vote dictionary is empty, your assignment seems to be backwards (assigning `win` to `vote` instead of the other way around), and that isn't how you access a dictionary anyway. You need to work harder on your example. – David Robinson Jun 01 '12 at 03:44

2 Answers2

3

The usual way would be

win = max(vote, key=vote.get)

You could also use a Counter

from collections import Counter
win, = Counter(vote).most_common(1)
John La Rooy
  • 281,034
  • 50
  • 354
  • 495
1
win = sorted(vote, key=lambda x: votes[x])[-1]

More info here: http://docs.python.org/library/functions.html#sorted

Mark Roberts
  • 452
  • 4
  • 6
  • You can also use `key` with `min()` and `max()`. If you only need the max or the min, they are more efficient `O(n)` compared to sorting `O(n log(n))` – John La Rooy Jun 01 '12 at 04:42