使用循环仅从字典中打印一个键

时间:2018-11-04 12:21:37

标签: python

我一直在学校从事此python作业,并且一直被困在这个特定的问题上。从给出的数据中,我想找出节省最多的人。

data = {
'Brad':5000, 
'Greg':8000, 
'Sarah':9000000, 
'Kim':6500000, 
'George':24000, 
'Ben':1000
  }

我的代码:

most_savings = 0

for person, savings in data.items():
    if savings > most_savings:
        most_savings = savings
        print(person,"has the most savings at",savings) 

打印输出为:

Brad has the most savings at 5000
Sarah has the most savings at 9000000

所需的输出:

Sarah has the most savings at 9000000

我没有得到想要的输出。我想知道我哪里出错了。在这里需要一些帮助。谢谢

1 个答案:

答案 0 :(得分:3)

不要循环打印-您将打印“此时”最丰富的一个。

most_savings = 0
pers = None 

# process all data, remembers pers and most_savings    
for person, savings in data.items():
    if savings > most_savings:
        most_savings = savings
        pers = person

 # print only the final result
 print(pers,"has the most savings at",most_savings)

您还可以使用内置的max()函数并指定一个lambda - function作为键函数,以便在决定内容时评估该项目的(键,)部分max()):

person, savings  = max( data.items(), key = lambda x:x[1])
print(person,"has the most savings at",savings)