python3 按字典的key和value排序


 
        
count_dict = {
    'b': 2,
    'h': 2,
    'c': 5,
    'e': 4,
    'w': 3,
    'q': 3,
    'a': 7,
}
#按value從小到大排序
a = sorted(count_dict.items(), key=lambda x: x[1])
#按value從大到小排序
a1 = sorted(count_dict.items(), key=lambda x: x[1], reverse=True)
#按key從小到大排序
a2 = sorted(count_dict.items(), key=lambda x: x[0])
#按key從大到小排序
a3 = sorted(count_dict.items(), key=lambda x: x[0], reverse=True)
#切片取vlaue最大的3個
a4 = a1[:3]

print(a)
print(a1)
print(a2)
print(a3)
print(a4)

#結果:
[('b', 2), ('h', 2), ('w', 3), ('q', 3), ('e', 4), ('c', 5), ('a', 7)]
[('a', 7), ('c', 5), ('e', 4), ('w', 3), ('q', 3), ('b', 2), ('h', 2)]
[('a', 7), ('b', 2), ('c', 5), ('e', 4), ('h', 2), ('q', 3), ('w', 3)]
[('w', 3), ('q', 3), ('h', 2), ('e', 4), ('c', 5), ('b', 2), ('a', 7)]
[('a', 7), ('c', 5), ('e', 4)]


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM