This is the dictionary I have currently:
{"214123" : 75.0,
"153525" : 60.0,
"734829" : 40.0,
"992832" : 89.0,
"823482" : 80.0}
I want to sort the values in dictionary in descending order, and after that, only show the top 3 values.
Expected output:
{"992832" : 89.0,
"823481" : 80.0,
"214123" : 75.0}
I'm using Python 3.0, and my current code is:
prices = []
data[listing_id] = price
for listing, price in data.items():
prices.append(price)
prices.sort(reverse=True)
top3 = prices[0:2]
From here I don't know how to assign my values back to the dictionary. What should I do? Thank you (-:
With 3.6+:
dict(sorted(list(d.items()), key=lambda p: p[1], reverse=True)[:3])
With < 3.6:
import collections
collections.OrderedDict(sorted(list(d.items()), key=lambda p: p[1], reverse=True)[:3])
Other option:
from heapq import nlargest
res = nlargest(3, h.items(), key=lambda x: x[1])
#=> [('992832', 89.0), ('823482', 80.0), ('214123', 75.0)]
To convert back to dict:
{ k[0]: k[1] for k in res } #=> {'992832': 89.0, '823482': 80.0, '214123': 75.0}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With