Home > other >  Sorting Elements in a List Based on Values
Sorting Elements in a List Based on Values

Time:07-03

I have a dictionary and I need the keys to be sorted according to their corresponding values. But the keys should not change the preset order when sorting is applied

The below example shows exactly what I am trying to do. The code returns the keys of first 3 highest values

Code

import heapq

val = {"a":3, "b":2, "c":4, "d":10, "e":6}

res = heapq.nlargest(3, val, key=val.get)
print(res)

Current Output

['d', 'e', 'c']

Expected Output

['c', 'd', 'e']

I tried this with heapq module but no use and usage of heapq module is not mandatory

CodePudding user response:

I don't think the heap is necessary here:

lookup_set = set(sorted(val.keys(), key=lambda x: val[x], reverse=True)[:3])
[i for i in val if i in lookup_set]

First creating a set of wanted keys, then filtering val.keys() to get the correct order.

yields:

['c', 'd', 'e']

To the people concerned of the ineffeciency of this:
O( n log n ) for sorting
O( n ) for making a set
O( n ) for linear filter of val keys afterwards.

Total O( n log n )

CodePudding user response:

Try this

import heapq
val = {"a":3, "b":2, "c":4, "d":10, "e":6}

res = sorted(heapq.nlargest(3, val, key=val.get))
print(res)

Output:

['c', 'd', 'e']
  • Related