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)]
原文地址:https://www.cnblogs.com/lhanghang/p/10295076.html