pythondictionarykeypopularity

how to find most and least popular product?


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?


Solution

  • 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).