Home > Net >  Get the N largest key value from a list of dictionary with Python
Get the N largest key value from a list of dictionary with Python

Time:07-30

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})

CodePudding user response:

It might be easier if you convert the list of dictionaries into one entire dictionary, with the dname as the keys. You can then access the keys of the dictionary in list form using list(dict.keys), sort the list of keys, then iterate through the dictionary using the list. However, this is a roundabout way, which might not be what you are looking for.

CodePudding user response:

Do you expect that performance will be an issue with the data set you have now or in the future. If not concentrate on the understandably of your code over speed. Isolate the way the data is stored from the processing of the data.
That way if the data structure has to change the rest of the code does not. This open the can of worms as to which technique to use (Object oriented, Functional,....) which is for another question.

  • Related