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?
答案 0 :(得分:4)
使用heap queue算法:
import heapq
y = {'a':55, 'b':33, 'c':67, 'd':12}
print heapq.nlargest(n=3, iterable=y, key=y.get)[-1]
# b
对于大型词典而言,这将比每次排序整个词典更好。具体来说,如果您要查找n
个最大元素的k
元素字典,则会在O(n log k)
而不是O(n log n)
中运行。
另请注意,这会按顺序为您提供所有三个最大值,只需删除[-1]
:
print heapq.nlargest(n=3, iterable=y, key=y.get)
# ['c', 'a', 'b']
答案 1 :(得分:2)
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's value from the dict
xth = stats[xth_key]
答案 2 :(得分:0)
>>> mydictionary = {'a':'1', 'b':'3', 'c':'2'}
>>> sorted_list = list(sorted(mydictionary, key=mydictionary.get))
>>> sorted_list[2]
'b'
答案 3 :(得分:0)
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