3

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

guymil
  • 63
  • 4
  • 1
    Dictionaries should generally not be used for storing ordered data.. _in most cases a sequence (ie. list) is a better data-structure to store the sorted result_. Regardless, OrderedDict and Python 3.6+'s (?) dict will "preserve insert order"; however, such functionality is not 'universal' across various languages and it may muddle ADT usages and confuse future coders or make expectations harder to maintain.. – user2864740 Dec 31 '18 at 19:49
  • 2
    Possible duplicate of [How do I sort a dictionary by value?](https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value) – meowgoesthedog Dec 31 '18 at 19:57

4 Answers4

3

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])
ic3b3rg
  • 14,629
  • 4
  • 30
  • 53
1

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}
iGian
  • 11,023
  • 3
  • 21
  • 36
0
d={"214123" : 75.0,
 "153525" : 60.0,
 "734829" : 40.0,
 "992832" : 89.0,
 "823482" : 80.0}
sorted_d = sorted(d.items(), key=lambda x: x[1], reverse=True)
print({x:y for x,y in sorted_d[0:3]})

Output

{'992832': 89.0, '823482': 80.0, '214123': 75.0}
Bitto
  • 7,937
  • 1
  • 16
  • 38
0

Dictionaries do not have a fixed order in Python. Every time you call the dictionary, there is a possibility that the order of the elements is different from the former call. You might find it easier to use 2 lists - one for the keys and one for the values where corresponding keys and values are at the same index. The slight drawback is that you will have to manually code the sort function so that it modifies both lists at the same time, but this has a simple fix. You can find the code for mergesort (the fastest) online and then modify it slightly (you should only need to add one line) so that it modifes both lists. Another collection type you can use are tuples but that would be more tricky as they are immutable.

SSEZ
  • 19
  • 3