Get x'th largest element in a dictionary

I am looking to get the largest element x in the dictionary from the corresponding key value.

For example, with a dictionary:

 y = {'a':55, 'b':33, 'c':67, 'd':12}

I want to be able to easily retrieve 'b'as the third largest key.

Initially, when I was only after the first three entries, I made a copy of the dictionary, found the maximum value (for example, the following Get the key with the maximum value in the dictionary? ), Deleted the key from the maximum value, and then started it again. When looking for more than a few of the highest values, this approach seems rather cumbersome. Is there an easy way to get the corresponding key for x'th largest element?

+4
source share
4 answers

Using the heap queue algorithm :

import heapq
y = {'a':55, 'b':33, 'c':67, 'd':12}
print heapq.nlargest(n=3, iterable=y, key=y.get)[-1]
# b

This will do better for large dictionaries than sort the entire dict each time. In particular, with a dictionary of items nwhere you are looking for the largest k, this is done in O(n log k)place of O(n log n).

Also note that this gives you all three of the biggest values โ€‹โ€‹as a list, just delete [-1]:

print heapq.nlargest(n=3, iterable=y, key=y.get)
# ['c', 'a', 'b']
+4
source
x = 2  # looking for second highest
stats = {'a':1000, 'b':3000, 'c': 100}
# the key of the xth highest
xth_key = sorted(stats, key=lambda s: stats[s])[x-1]  
# it value from the dict
xth = stats[xth_key]
+2
source
>>> mydictionary = {'a':'1', 'b':'3', 'c':'2'}
>>> sorted_list = list(sorted(mydictionary, key=mydictionary.get))
>>> sorted_list[2]
'b'
0
source
def get_xth_largest_item_from_dict(dct, x=1):

    l =[(v, k) for k,v in dct.items()]
    l.sort(reverse=True)

    return l[x-1][1]

y = {'a':55, 'b':33, 'c':67, 'd':12}

print get_xth_largest_item_from_dict(y, 1) # c
print get_xth_largest_item_from_dict(y, 3) # b
0
source

All Articles