0

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})
1
  • Using lists of dictionary with strings as keys to represent dataframe is not efficient. Did you look Pandas or eventually Numpy? They have function to compute a partition and they can store this dataframe in a much more efficient way in memory (especially Pandas which is designed for that). That being said, for very small dataframes (eg. 5 entries and 3 columns), Pandas is slow. Commented Jul 29, 2022 at 21:21

2 Answers 2

0

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.

0

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.