[英]Printing only one Key from a Dictionary using loop
Ive been working on this python assignment in school and was stucked at this particular question given to me. 我在学校里一直在做这个Python作业,并且一直被困在给我的这个特定问题上。 From the data given, I would want to find out the person with the most savings.
从给出的数据中,我想找出最省钱的人。
data = {
'Brad':5000,
'Greg':8000,
'Sarah':9000000,
'Kim':6500000,
'George':24000,
'Ben':1000
}
My code: 我的代码:
most_savings = 0
for person, savings in data.items():
if savings > most_savings:
most_savings = savings
print(person,"has the most savings at",savings)
printed output was: 打印输出为:
Brad has the most savings at 5000
Sarah has the most savings at 9000000
desired output: 所需的输出:
Sarah has the most savings at 9000000
Im not getting my desired output. 我没有得到我想要的输出。 I would like to know where did i go wrong.
我想知道我哪里出错了。 Need some help here.
在这里需要一些帮助。 Thanks
谢谢
Dont print in a loop - you will print the "at this time" richest one. 不要循环打印-您将打印“此时”最丰富的内容。
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)
You can also use the built in max()
function and specify a lambda - function as keyfunction that evaluates the (key, value ) part of the item into account when deciding whats max() ): 您还可以使用内置的
max()
函数并指定一个lambda函数作为键函数 ,该函数将在决定什么是max()时评估项目的(key, value )部分:
person, savings = max( data.items(), key = lambda x:x[1])
print(person,"has the most savings at",savings)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.