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:

Python Dictionary: Get the top three items in a shop.

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:

Previous: Write a Python program to remove spaces from dictionary keys.
Next: Write a Python program to get the key, value and item in a dictionary.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/dictionary/python-data-type-dictionary-exercise-30.php