-1

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

  • 1
    What do you mean by "dictionary list"? `kcaldict` is just a dictionary, there's no list. – Barmar Oct 04 '22 at 06:03
  • `kcaldict.values())` doesn't make use of `dict`. You're just calculating the same maximum every time through the list comprehension. It also doesn't depend on `key` and `value`. – Barmar Oct 04 '22 at 06:06

1 Answers1

0

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)")
Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
Deepak Tripathi
  • 3,175
  • 1
  • 8
  • 21