[Solved] How can I extract two most expensive items from a dictionary using standard library? [closed]


You could sort the list of dictionaries by the price reversed and then use slicing notation to return the top results.

from operator import itemgetter

top = 3
data = [{"name": "bread", "price": 100},
       {"name": "wine", "price": 138},
       {"name": "meat", "price": 15},
       {"name": "water", "price": 1},
       {"name": "fish", "price": 10}]

print(sorted(data, key=itemgetter('price'), reverse=True)[:top])

Output:

[{'name': 'wine', 'price': 138}, 
{'name': 'bread', 'price': 100}, 
{'name': 'meat', 'price': 15}]

2

solved How can I extract two most expensive items from a dictionary using standard library? [closed]