- 单独用sorted
# sorted的参数
sorted(iterable, /, *, key=None, reverse=False)
from random import randint
data = {_:randint(80,100) for _ in 'zyxbca'} # 推导表达式+随机数生成字典值
print(data) # {'z': 84, 'y': 81, 'x': 80, 'b': 83, 'c': 91, 'a': 93}
data = sorted(data.items(),key=lambda x:x[1]) # 传入字典的项,根据项的值排序
print(data) #{'x': 80, 'y': 81, 'b': 83, 'z': 84, 'c': 91, 'a': 93}
2.sorted + zip
from random import randint
# {'z': 84, 'y': 81, 'x': 80, 'b': 83, 'c': 91, 'a': 93}
data = {_:randint(80,100) for _ in 'zyxbca'} # 推导表达式+随机数生成字典值
print(data)
print(list(zip(data.values(),data.keys()))) # [(84, 'z'), (81, 'y'), (80, 'x'), (83, 'b'), (91, 'c'), (93, 'a')]
data = sorted(zip(data.values(),data.keys())) # 列表,元素是元祖,按元组第一项排序
data = {v:k for k,v in data} # 利用字典推导表达式把列表变成字典
print(data) # {'x': 80, 'y': 81, 'b': 83, 'z': 84, 'c': 91, 'a': 93}