﻿ Python: Get the top three items in a shop - w3resource

# Python: Get the top three items in a shop

## Python dictionary: Exercise-30 with Solution

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

Visual Presentation:

Sample Solution:

Python Code:

``````# Import the 'nlargest' function from the 'heapq' module and the 'itemgetter' function from the 'operator' module.
from heapq import nlargest
from operator import itemgetter

# Create a dictionary 'items' with keys representing items and values as their corresponding prices.
items = {'item1': 45.50, 'item2': 35, 'item3': 41.30, 'item4': 55, 'item5': 24}

# Use the 'nlargest' function to find the three items with the largest prices from the 'items' dictionary.
# The 'key' argument specifies that the second element (price) of each key-value pair should be used for comparison.
for name, value in nlargest(3, items.items(), key=itemgetter(1)):
# Print the name and price of the three items with the largest prices.
print(name, value)
```
```

Sample Output:

```item4 55
item1 45.5
item3 41.3
```

Python Code Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿