2016-07-05 154 views
1

因此,如果项目值相同,我想根据值对字典进行排序并按字母顺序维护。但是,python字典不会按字母顺序保存数据,如何解决它?先谢谢你!Python:按值排序字典,同时保持按字母顺序排列

这里是我的代码:

from collections import Counter 
test = "betty bought a bit of butter but the butter was bitter" 
Counter(test.split()).most_common(3) 

输出:

[('butter', 2), ('a', 1), ('bitter', 1)] 

所需的输出应该是:

[('butter', 2), ('a', 1), ('betty', 1)] 

自认为 '苦' 应该是背后的 '贝蒂' 按字母顺序。

回答

3

使用heapq.nsmallest() function与自定义键,在计数传递反转排序的那一部分,和密钥本身按字母顺序返回:

import heapq 

top3 = heapq.nsmallest(
    3, Counter(test.split()).items(), 
    key=lambda kv: (-kv[1], kv[0])) 

Counter.most_common()方法使用heapq.nlargest()当你给它的参数小于字典中的键的数量,并且只使用计数来确定顺序时,所以在绑定的情况下,顺序是任意的。以上内容与您的特定排序顺序相同。就像Counter.most_common()一样,这是一个O(NlogK)解决方案(N是计数的项目数量,K是您希望输出的项目数量)。

演示:

>>> import heapq 
>>> from collections import Counter 
>>> test = "betty bought a bit of butter but the butter was bitter" 
>>> heapq.nsmallest(3, Counter(test.split()).items(), key=lambda kv: (-kv[1], kv[0])) 
[('butter', 2), ('a', 1), ('betty', 1)] 
1

或者 - 你可以混合CounterOrderedDict

from collections import Counter, OrderedDict 

class OrderedCounter(Counter, OrderedDict): 
    pass 

test = "betty bought a bit of butter but the butter was bitter" 
mc = OrderedCounter(sorted(test.split())).most_common(3) 
# [('butter', 2), ('a', 1), ('betty', 1)] 
+0

这需要一个完整的O(NlogN)排序,**除了**到O(NlogK) heapq调用'most_common'使得。 –

+0

@MartijnPieters我当然没有提出效率的要求 - 这只是一种替代方法,在其他情况下可能有用...... –