Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I sort values in dictonary on Python?

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 (-:

like image 574
guymil Avatar asked Jun 12 '26 22:06

guymil


2 Answers

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])
like image 113
ic3b3rg Avatar answered Jun 15 '26 23:06

ic3b3rg


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}
like image 22
iGian Avatar answered Jun 15 '26 23:06

iGian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!