在字典中查找最大值的关键字

时间:2014-09-26 03:32:37

标签: python-3.x dictionary output

基本上我有这个代码,我需要一个特定的输出,其中我说明了获胜者和他的投票数。我似乎已经找到了最大值,但不是关键的对应物。错误发生在我的倒数第二个输出中。让我知道你们的想法,这可能是一个简单的解决方法,谢谢你!

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

1 个答案:

答案 0 :(得分:1)

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