Shaydrian Tan
Shaydrian Tan

Reputation: 21

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. 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

Upvotes: 0

Views: 57

Answers (1)

Patrick Artner
Patrick Artner

Reputation: 51643

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() ):

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

Upvotes: 3

Related Questions