且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

获得从排序字典到另一个的第一个N个键对

更新时间:2023-11-23 09:25:22

OrderedDict的主要目的是保留创建元素的顺序。
你想要的是 collections.Counter ,内置了最常见的功能:

The primary purpose of OrderedDict is retaining the order in which the elements were created. What you want here is collections.Counter, which has the n-most-frequent functionality built-in:

>>> dictionary={'a':10,'b':20,'c':30,'d':5}
>>> import collections
>>> collections.Counter(dictionary).most_common(2)
[('c', 30), ('b', 20)]