python中一般对字典按照key随机排序,实际应用中我们可能需要根据value排序,大致的有如下几种方法:
1、内置sorted函数排序
from random import randint
随机创建字典
dict1 = {x:randint(60,100) for x in 'shdlqa'}
print(dict1)
# 从大到小排序
dict2 = sorted(dict1.items(), key=lambda x:x[1], reverse=True)
print(dict2)
#默认从小到大排序
dict3 = sorted(dict1.items(), key=lambda x:x[1])
print(dict3)
输出结果如下:
{'s': 72, 'h': 71, 'd': 90, 'l': 77, 'q': 64, 'a': 87}
[('d', 90), ('a', 87), ('l', 77), ('s', 72), ('h', 71), ('q', 64)]
[('q', 64), ('h', 71), ('s', 72), ('l', 77), ('a', 87), ('d', 90)]
2、利用operator和sorted函数排序
from random import randint
import operator
dict1 = {x:randint(60,100) for x in 'shdlqa'}
print(dict1)
#默认从小打到排序
dict4 = sorted(dict1.items(), key=operator.itemgetter(1))
print(dict4)
#输出结果如下:
{'s': 72, 'h': 71, 'd': 90, 'l': 77, 'q': 64, 'a': 87}
[('q', 64), ('h', 71), ('s', 72), ('l', 77), ('a', 87), ('d', 90)]
3、利用zip元祖排序
from random import randint
dict1 = {x:randint(60,100) for x in 'shdlqa'}
print(dict1)
# 利用zip分装成元祖排序
data = zip(dict1.values(), dict1.keys())
#默认从小到大排序
dict5 = sorted(data)
print(dict5)
#输出结果如下:
{'s': 72, 'h': 71, 'd': 90, 'l': 77, 'q': 64, 'a': 87}
[(64, 'q'), (71, 'h'), (72, 's'), (77, 'l'), (87, 'a'), (90, 'd')]