一、按键(key)排序

dict = {2:'b', 4:'d', 3:'c', 1:'a'}

# 只显示key
new_dict = sorted(dict)
print(new_dict)

# 只显示key
new_dict = sorted(dict.keys())
print(new_dict)

# 显示key和value
new_dict = sorted(dict.items(), reverse=True)
print(new_dict)

# 显示key和value
new_dict = sorted(dict.items(), key=lambda b: b[0], reverse=True)
print(new_dict)

结果:

[1, 2, 3, 4]
[1, 2, 3, 4]
[(4, 'd'), (3, 'c'), (2, 'b'), (1, 'a')]
[(4, 'd'), (3, 'c'), (2, 'b'), (1, 'a')]

二、按值(value)排序

dict = {2:'b', 4:'d', 3:'c', 1:'a'}

# 只显示value
new_dict = sorted(dict.values())
print(new_dict)

# 显示key和value
new_dict = sorted(dict.items(), key=lambda b: b[1], reverse=True)
print(new_dict)

结果:

['a', 'b', 'c', 'd']
[(4, 'd'), (3, 'c'), (2, 'b'), (1, 'a')]