Top Three Items in a Shop

Write a Python program to get the top three items in a shop.

Example 1:

Input: {"item1": 45.50, "item2": 35.50, "item3": 41.30, "item4": 55.40, "item5": 24.50} 
Output: [("item4", 55.40), ("item1", 45.50), ("item3", 41.30)]

Example 2:

Input: {"item1": 22.50, "item2": 25.50, "item3": 27.30, "item4": 22.40, "item5": 29.50} 
Output: [("item5", 29.50), ("item3", 27.30), ("item2", 25.50)]

Use the built-in sorted() function in combination with the items() method of the dictionary and a lambda function as the key parameter.

def top_three_items(d):
    return sorted(d.items(), key=lambda x: x[1], reverse=True)[:3]

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!