0

I'd like to know if you know other/better way (without max method) to get a key with the biggest score in a dictionary ? :

report_card = {'french' : 14,
            'english' : 12,
            'math' : 16,
            'chemistry' : 19,
            'sport' : 14}
max = 0

for subject, score in report_card.items():
    if max < report_card[subject]:
        max = report_card[subject]

for subject, score in report_card.items():
    if max == report_card[subject]:
        print(f"The subject with the highest score is {subject} with {score} points")
  • And why without the max function? – yatu Jun 09 '19 at 17:43
  • keeping the running max which you are doing is perhaps the best way – Devesh Kumar Singh Jun 09 '19 at 17:44
  • 2
    Possible duplicate of [Getting key with maximum value in dictionary?](https://stackoverflow.com/questions/268272/getting-key-with-maximum-value-in-dictionary). There are at least 4 or 5 answers that don't use `max` on this thread. – ggorlen Jun 09 '19 at 17:51
  • I didn't want use 'max' just for training my logic and for fun (I start programming) –  Jun 10 '19 at 19:08

2 Answers2

0

Somewhat simpler, but please, the max function is there for a reason.

report_card = {'french' : 14,
            'english' : 12,
            'math' : 16,
            'chemistry' : 19,
            'sport' : 14}
max = 0
max_s = ""

for subject, score in report_card.items():
    if max < score:
        max = score
        max_s = subject

print(f"The subject with the highest score is {max_s} with {max} points")
Christian Sloper
  • 7,440
  • 3
  • 15
  • 28
0

Try this:

max(report_card.items(), key=lambda x: x[1])[0]

dict.items() return all values as pairs. max returns maximum value of an iterable. key keyword allows you to pass function, that produces value for each item to compare for maximum. max function will return one of values produced by report_card.items() (not value produced by key functor), so you need [0] to get key from it.

Radosław Cybulski
  • 2,952
  • 10
  • 21