python3 怎么取字典里最后一个 key

2019-01-02 21:42发布

问题:

d = {19: 7, 31: 6, 28: 5, 16: 5, 32: 5, 2: 4, 24: 4, 29: 4, 6: 4, 18: 4, 15: 4, 12: 4}

我是用 collections.Counter 排序的。
排序后字典中 value 是按降序的,它在我这里表示出现最少的概率,,
所以我只要最后一个 key (就是出现概率最少的 key )

o数据量也比较大,现在有几千条,以后可能会增加

回答1:

不知道这个是不是你想要的。

from collections import OrderedDict

your_dict = {19: 7, 31: 6, 28: 5, 16: 5, 32: 5, 2: 4, 24: 4, 29: 4, 6: 4, 18: 4, 15: 4, 12: 4}
order_of_keys = your_dict.keys()
list_of_tuples = [(key, your_dict[key]) for key in order_of_keys]
your_dict = OrderedDict(list_of_tuples)

print(next(reversed(your_dict)))


回答2:

d = {19: 7, 31: 6, 28: 5, 16: 5, 32: 5, 2: 4, 24: 4, 29: 4, 6: 4, 18: 4, 15: 4, 12: 4}
list(d)[-1]
时间复杂度O(n)



标签: