2014-09-26 63 views
0

基本上我有这个代码,我需要一个具体的输出,我说明赢家和他的票数。我似乎已经找到了最大价值的一切,但不是它的关键对手。该错误是在我的倒数第二个输出。让我知道你们的想法,这可能是一个简单的解决方法,谢谢你!寻找字典中的最大值的关键

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() 
+0

既然你只是在寻找赢家,你为什么要储存其他人在一本字典?只要跟踪获胜者的名字和他们得到的两个变量的分数,然后最后只需打印这些。此外,要打印该号码,请做'str(赢家)' – smac89 2014-09-26 03:37:27

+0

ughhh。好的。这就说得通了。所以, 如果获胜者<投票: 获胜者=投票, 是为投票,但那么关键?或者有没有办法只存储最大值。谢谢 – Cooper 2014-09-26 03:40:42

+0

,我必须循环浏览,因为我需要输出每个百分比和投票。 了解它:如果获胜者<投票: 获胜者=投票 who =名称 – Cooper 2014-09-26 03:53:40

回答

1
import operator 
dic = {'a':1000, 'b':3000, 'c': 100} 
max(dic.items(), key=operator.itemgetter(1))[0]