因此,如果项目值相同,我想根据值对字典进行排序并按字母顺序维护。但是,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)]
自认为 '苦' 应该是背后的 '贝蒂' 按字母顺序。
这需要一个完整的O(NlogN)排序,**除了**到O(NlogK) heapq调用'most_common'使得。 –
@MartijnPieters我当然没有提出效率的要求 - 这只是一种替代方法,在其他情况下可能有用...... –