A dictionary has no sort() method. Instead, you sort its (key, value) pairs with sorted() and build a new dictionary from the result.
The program
python
stock = {"banana": 12, "apple": 30, "cherry": 5, "mango": 18}
by_value = dict(sorted(stock.items(), key=lambda item: item[1]))
print(by_value)
largest_first = dict(sorted(stock.items(), key=lambda item: item[1], reverse=True))
print(largest_first)output
{'cherry': 5, 'banana': 12, 'mango': 18, 'apple': 30}
{'apple': 30, 'mango': 18, 'banana': 12, 'cherry': 5}How it works
stock.items()gives pairs such as("banana", 12).key=lambda item: item[1]tellssorted()to compare the pairs by their second part, the value.item[0]would be the key.sorted()returns a list of pairs.dict(...)turns it back into a dictionary, and a dictionary keeps that order.reverse=Truesorts from largest to smallest.
Sort by key, or keep only the top few
python
stock = {"banana": 12, "apple": 30, "cherry": 5, "mango": 18}
print(dict(sorted(stock.items())))
top_two = sorted(stock.items(), key=lambda item: item[1], reverse=True)[:2]
for fruit, count in top_two:
print(fruit, count)output
{'apple': 30, 'banana': 12, 'cherry': 5, 'mango': 18}
apple 30
mango 18Without a key, pairs are compared by their first part, so sorted(stock.items()) sorts by key in alphabetical order.