Reputation: 13
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}]
Upvotes: 0
Views: 86
Reputation: 26325
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}]
Upvotes: 1
Reputation: 7510
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]
Upvotes: 2
Reputation: 5026
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}]
Upvotes: 2