python - Obtain x'th largest item in a dictionary -
i looking obtain x'th largest item in dictionary key's corresponding value.
for example, dictionary:
y = {'a':55, 'b':33, 'c':67, 'd':12} i want able extract 'b' 3rd largest key.
initially, when after top 3 occurrences, made copy of dictionary, found max value (e.g. following getting key maximum value in dictionary?), removed key max value, , re-ran. when looking more several highest values, approach seems quite cumbersome. there simple way of getting corresponding key x'th largest item?
using 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 better performing large dictionaries sorting entire dict each time. specifically, dictionary of n elements you're looking k largest ones, runs in o(n log k) instead of o(n log n).
also note gives 3 largest values in order list, remove [-1]:
print heapq.nlargest(n=3, iterable=y, key=y.get) # ['c', 'a', 'b']
Comments
Post a Comment