May I know whether there is straight forward/compact appraoch to extract the N largest key value from a list of dictionary with Python
While the approach below produced the desirable result, but I wonder whether there is better alternative.
from heapq import nlargest
from operator import itemgetter
dls=[{'dname': 'a', 'text': 'CC', 'dscore': 0.3},
{'dname': 'b', 'text': 'CC', 'dscore': 0.1},
{'dname': 'c', 'text': 'CC', 'dscore': 0.9},
{'dname': 'd', 'text': 'CC', 'dscore': 0.2},
{'dname': 'e', 'text': 'CC', 'dscore': 0.102}]
ls=[d['dscore'] for d in dls ]
nlargest=nlargest(3, range(len(ls)), key=ls.__getitem__)
print(itemgetter(*sorted(nlargest))(dls))
Output
({'dname': 'a', 'text': 'CC', 'dscore': 0.3}, {'dname': 'c', 'text': 'CC', 'dscore': 0.9}, {'dname': 'd', 'text': 'CC', 'dscore': 0.2})