-4

I have this: {code:[name,price,units]}

I want to print the name of the Product with the highest value.

I have tried this but i can only get the higher price

products = {1:["Product1",8000.0,65], 2:["Product2",2300.0,15], 3:["Product3",2500.0,38], 
    4:["Product4",9300.0,55], 5:["Product5",2100.0,42]}

higher=0
for code in products:             
    if products[code][1]>higher:                       
       higher=products[code][1]
print(higher)
9300.0

When I try to show the name of the product with higher=products[code][0] I get an error

TypeError: '>' not supported between instances of 'float' and 'str'
  • Your `for` loop is not right. You should iterate over `key` `value` pair. Not like iterating over a list. I think [this](https://stackoverflow.com/questions/3294889/iterating-over-dictionaries-using-for-loops) will help you understand. – Tony Jun 28 '21 at 08:37

2 Answers2

0

When you write products[code] you are getting a list, for instance:

["Product1",8000.0,65]

Therefore, if you try to access index 0 (through products[code][0]) you will receive "Product1" which you can't compare using > because that's a string and which value is really "bigger" than the other?

Not sure what you are trying to compare, but the possibilities to compare here are:

if products[code][1] > higher
if products[code][2] > higher

Hope this helps.

Edit:

After understanding you want to print the name of that product, all you need to do is to add

highest_product = products[code]

inside of your for loop and then print it to show all the product details, or just print(highest_product[0]) for the name only.

Your final code should look like this:

products = {1:["Product1",8000.0,65], 2:["Product2",2300.0,15], 3:["Product3",2500.0,38], 
    4:["Product4",9300.0,55], 5:["Product5",2100.0,42]}

higher = 0
for code in products:             
    if products[code][1] > higher:                       
       higher=products[code][1]
       highest_product = products[code]

# Prints all the product's details
print(highest_product)

# Prints just the name of the highest product
print(highest_product[0])
OmerM25
  • 243
  • 2
  • 13
0

One liner using builtin max and a lambda function

products = {1: ["Product1", 8000.0, 65], 2: ["Product2", 2300.0, 15], 3: ["Product3", 2500.0, 38],
            4: ["Product4", 9300.0, 55], 5: ["Product5", 2100.0, 42]}

_max_by_second_element = max(products.values(), key=lambda x: x[1])
print(_max_by_second_element)
_max_by_third_element = max(products.values(), key=lambda x: x[2])
print(_max_by_third_element)

output

['Product4', 9300.0, 55]
['Product1', 8000.0, 65]
balderman
  • 22,927
  • 7
  • 34
  • 52