0

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

  • 1
    The question is, do you want to output something as soon as you find a person whose income is greater than that of _some_ other person? Or do you want to output only when you're sure that person's income is _the biggest_? – ForceBru Nov 04 '18 at 12:25

1 Answers1

3

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)
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
  • Thanks Patrick for the swift help. Ive gotten the results that i want. But just for added knowledge, how can get the same result but this time round using **Def** and **return** function? – Shaydrian Tan Nov 04 '18 at 12:35
  • `def get_max_savings(savingdata): return max( savingdata.items(), key = lambda x:x[1])` ? If you are unfamiliar with how functions works, read [this](https://docs.python.org/3/tutorial/controlflow.html#defining-functions) -you provide parameters to the functions, use those and return a result-if you return nothing the function returns `None` automatically (f.e. if your function just prints smth) – Patrick Artner Nov 04 '18 at 12:41