0

What I have is a list of dict:

x = [{25: 16}, {40: 32}, {11: 50}]

What i am trying is to sort it by value and get the top n elements:

where n = 2

what i did:

sorted_lst = x.sort(key=lambda d: d.values)
print(sorted_lst)
filtered = sorted_lst[:n]

but this did not work.

the output that I am trying to get is:

[{11: 50}, {40: 32}]
Tibebes. M
  • 6,940
  • 5
  • 15
  • 36
Jack Lee
  • 13
  • 1

3 Answers3

2

Without iterator in lambda

x = [{25: 16}, {40: 32}, {11: 50}]
sorted(x, key = lambda i: list(i.values()), reverse = True)[:2]
>>> [{11: 50}, {40: 32}]
Michael Szczesny
  • 4,911
  • 5
  • 15
  • 32
  • Is it better without iter? like sorted(x, key = lambda x: next(iter(x.values())), reverse=True)[:2] – Christian Sloper Sep 20 '20 at 10:19
  • 1
    For me it is more readable and i don't have to know what `next(iter(...))`does. But I like your solution, too. Perhaps post as answer and let the voting system decide? – Michael Szczesny Sep 20 '20 at 10:21
2

Here is a slightly different solution to @mikksu's variant, using iter and next. Iter turns the view of values into an iterator and next gets the first value.

sorted(x, key = lambda x: next(iter(x.values())), reverse=True)[:2]
Christian Sloper
  • 7,440
  • 3
  • 15
  • 28
1

You could use collections.Counter.most_common to get the top n elements:

>>> from collections import Counter
>>> lst = [{25: 16}, {40: 32}, {11: 50}]
>>> [{k: v} for k, v in Counter(dict(tuple(*d.items()) for d in lst)).most_common(2)]
[{11: 50}, {40: 32}]
RoadRunner
  • 25,803
  • 6
  • 42
  • 75