2016-08-13 33 views
0

我是一名Python初学者。我写了一个代码,其中参赛者的姓名和他们的分数将存储在字典中。让我把这本词典称为results。不过,在编写代码时我已将它留空。当程序运行时,键和值将被添加到字典中。如何比较带有未知键的字典的值?

results={}  
name=raw_input() 
    #some lines of code to get the score# 
results[name]=score 
    #code# 
name=raw_input() 
    #some lines of code to get the score# 
results[name]=score 

程序执行后,让我们说results == {"john":22, "max":20}

我想比较约翰和最大的成绩,并宣布与得分最高的冠军的人。但是在节目开始时我不会知道参赛者的姓名。那么我怎样才能比较分数,并宣布其中一人为胜利者。

+0

names = [];在results.iterkeys()中输入名称:names.append(name) – Ananth

+0

您想在字典中获得最高分数吗? – Arman

+1

请参阅http://stackoverflow.com/questions/268272/getting-key-with-maximum-value-in-dictionary – Seba

回答

1

下面是一个实现你想要的工作示例,它基本上是从字典中获取最大的项目。在这个例子中,你还可以看到其他的宝石一样产生决定性的随机值,而不是手动将他们和获得最小值,在这里你去:

import random 
import operator 

results = {} 

names = ["Abigail", "Douglas", "Henry", "John", "Quincy", "Samuel", 
     "Scott", "Jane", "Joseph", "Theodor", "Alfred", "Aeschylus"] 

random.seed(1) 
for name in names: 
    results[name] = 18 + int(random.random() * 60) 

sorted_results = sorted(results.items(), key=operator.itemgetter(1)) 

print "This is your input", results 
print "This is your sorted input", sorted_results 
print "The oldest guy is", sorted_results[-1] 
print "The youngest guy is", sorted_results[0] 
2

你可以做这个,让获奖者:

max(results, key=results.get) 
0

你可以这样做:

import operator 
stats = {'john':22, 'max':20} 
maxKey = max(stats.items(), key=operator.itemgetter(1))[0] 
print(maxKey,stats[maxKey]) 

你也可以得到最大的元组作为一个整体是这样的:

maxTuple = max(stats.items(), key=lambda x: x[1]) 

希望它有帮助!