Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obtain x'th largest item in a dictionary

I am looking to obtain the x'th largest item in a dictionary from the key's corresponding value.

For example, with the dictionary:

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

I want to be able to easily extract 'b' as the 3rd largest key.

Initially, when I was only after the top three occurrences, I made a copy of the dictionary, found the max value (e.g. following Getting key with maximum value in dictionary?), removed the key from the max value, and then re-ran. When looking for more than several highest values, this approach seems quite cumbersome. Is there a simple way of getting the corresponding key for the x'th largest item?

like image 637
kyrenia Avatar asked Apr 29 '15 00:04

kyrenia


People also ask

How do you find the largest value in a dictionary?

Python find highest value in dictionary By using the built-in max() method. It is provided with the 'alpha_dict' variable to obtain the highest value from and to return the key from the given dictionary with the highest value, the dict. get() method is used.

How do you find the value of the key in a dictionary?

You can use the get() method of the dictionary ( dict ) to get any default value without an error if the key does not exist. Specify the key as the first argument. The corresponding value is returned if the key exists, and None is returned if the key does not exist.


1 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 be better performing for large dictionaries than sorting the entire dict each time. Specifically, with a dictionary of n elements where you're looking for the k largest ones, this runs in O(n log k) instead of O(n log n).

Also note that this gives you all three largest values in order as a list, simply remove the [-1]:

print heapq.nlargest(n=3, iterable=y, key=y.get)
# ['c', 'a', 'b']
like image 122
tzaman Avatar answered Sep 27 '22 21:09

tzaman