Python 如何将字典的值与未知键进行比较?
我是Python的初学者。我已经写了一个代码,参赛者的名字和他们的分数将存储在一个字典里。让我把字典称为Python 如何将字典的值与未知键进行比较?,python,dictionary,Python,Dictionary,我是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 t
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}
我想比较一下约翰和马克斯的得分,并宣布得分最高的人为获胜者。但我不会在节目开始时知道参赛者的名字。因此,我如何比较分数,并宣布其中一个为优胜者。这里有一个实现您所需的工作示例,基本上就是从字典中获取最大项。在本例中,您还将看到其他gem,如生成确定性随机值,而不是手动插入它们并获取最小值,如下所示:
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]
下面是一个实现所需功能的工作示例,基本上就是从字典中获取最大项。在本例中,您还将看到其他gem,如生成确定性随机值,而不是手动插入它们并获取最小值,如下所示:
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]
您可以这样做,以获得赢家:
max(results, key=results.get)
您可以这样做,以获得赢家:
max(results, key=results.get)
你可以做:
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])
希望有帮助 您可以执行以下操作:
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])
希望有帮助 名称=[];对于results.iterkeys()中的name:names.append(name)要在字典中获得最高分数吗?请参阅names=[];对于results.iterkeys()中的name:names.append(name)要在字典中获得最高分数吗?请参阅