0

I'm trying to output the most popular and least popular item a store has sold. The items include: beef,chicken,egg,tuna. In my code, I've declared the variables:

beef = 0
egg= 0
tuna = 0
chicken= 0

and when a customer purchases a particular item, it would be beef+=1 and so on. My current problem is that i dont know how to display the name of the most sold item as the function min() and max() would only show the values of thew variables. I've even tried using a dictionary where the code was:

itemsList = [beef,egg,tuna,chicken]
mostPopular = max(itemsList)
items = {"Beef":beef,"Egg":egg","Tuna":tuna,"Chicken":chicken}
for key, value in items:
 if mostPopular == value:
  print(key)

unfortunately, this does not work as i would receive the error "too many values to unpack" :// is there another way to obtain the most popular item?

kriloots
  • 69
  • 9
  • Does this answer your question? [Getting key with maximum value in dictionary?](https://stackoverflow.com/questions/268272/getting-key-with-maximum-value-in-dictionary) – Grismar Nov 09 '20 at 02:28
  • This is the correct way of going over a dictionary's item ``for key, value in items.items(): ..." – Sep Nov 09 '20 at 02:28

1 Answers1

2

You were almost there:

for key, value in items.items():

By default iterating over a dictionary only gives you the keys. You have to call dict.items() to get key-value pairs.

You could've also imported collections.Counter and printed Counter(items).most_common(1).

orlp
  • 112,504
  • 36
  • 218
  • 315