How do I get the maximum of a dictionary list?

Question:

Hello guys I’m new in python and I’m trying to get the item with the highest kcalorie from a dictionary list but the outout isn’t correct can I know what’s the problem

maxkcal = int()
kcaldict = { 'udon':300,'salad':150,'gyudon':500,'pasta':450}
print("The menu is:")
for key,value in kcaldict.items():
    print(key,value)
    maxkcal = max([max(kcaldict.values()) for dict in kcaldict])
print("The food with the highest calorie on the menu is :" ,key, maxkcal,"(Kcal)")

the output is :

The menu is:
udon 300
salad 150
gyudon 500
pasta 450
The food with the highest calorie on the menu is : pasta 500 (Kcal)

but it’s supposed to be gyudon 500 not pasta

Asked By: Hazem Majeek

||

Answers:

You can try using max:

kcaldict = { 'udon':300,'salad':150,'gyudon':500,'pasta':450}
max_key, max_val = max(kcaldict.items(), key=lambda x: x[1])
print("The food with the highest calorie on the menu is :" ,max_key, max_val,"(Kcal)")

As pointed out in the comments, I have changed the code a little bit now it will work fine.

Your code should be like this:

import sys
maxkcal = -sys.maxsize
maxkcal_key = None
kcaldict = { 'udon':300,'salad':150,'gyudon':500,'pasta':450}
print("The menu is:")
for key,value in kcaldict.items():
    print(key,value)
    if value > maxkcal:
        maxkcal = value
        max_key = key
print("The food with the highest calorie on the menu is :" ,max_key, maxkcal,"(Kcal)")
Answered By: Deepak Tripathi
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.