2016-08-13 51 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]) 

希望它有幫助!