0

Basically i have this code, and i need a specific output where i state the winner and his number of votes. I seem to have everything down with finding the max value but not it's key counterpart. The error is in my second to last output. Let me know what you guys think, it's probably an easy fix and thank you!!!

print()
print()
print()
import sys
fo = open(sys.argv[1], "r")
dic = {}
count = 0
winner = 0

print("Candidates".center(15), "Votes".rjust(10), "Percent".rjust(10))
print("==========".center(15), "=====".rjust(10), "=======".rjust(10))

for line in fo:
    line = line[:-1]
    x = line.split(" ")
    names = (x[0]) + " " + (x[1])
    votes = int(x[2]) + int(x[3]) + int(x[4]) + int(x[5])
    dic[names] = votes
    count = votes + count
    if winner < votes:
        winner = votes

for i in dic.keys():
    percent = int((dic[i]/count)*100.00)
    print (i.center(15),str(dic[i]).center(15),str(percent)+"%")

#Loop through every kid and find percentage, 
print()
print("The winner is", "" , "with", winner, "votes!")
print()
print("Total votes polled:", count)
print()
print()
print()
Soup
  • 23
  • 1
  • 6
  • Since you are only looking for the winner, why are you storing everyone else in a dictionary? Just keep track of the winner's name and the score they got in two variables, then in the end simply print these. Also to print the number, do this `str(winner)` – smac89 Sep 26 '14 at 03:37
  • ughhh. okay. that makes sense. so, if winner < votes: winner = votes, is for the votes but then what about for the key??? or is there a way to only store the max value. thank you – Soup Sep 26 '14 at 03:40
  • and i have to loop through because i need to output the percentages and votes each have. got it: if winner < votes: winner = votes who = names – Soup Sep 26 '14 at 03:53
  • To keep track of the name, just declare a variable that will hold name. When you get a new max score for winner, also update the name variable to the name of the person with that score – smac89 Sep 26 '14 at 04:02
  • possible duplicate of [Getting key with maximum value in dictionary?](http://stackoverflow.com/questions/268272/getting-key-with-maximum-value-in-dictionary) – dawg Sep 26 '14 at 14:13

1 Answers1

1
import operator
dic = {'a':1000, 'b':3000, 'c': 100}
max(dic.items(), key=operator.itemgetter(1))[0]
dawg
  • 98,345
  • 23
  • 131
  • 206