给定一个字典,如:
x = {'a':1,'b':4,'c':3}
然后分别按键 和 值排序。
1、按键排序:
# 对字典x排序
x = {'a':1,'b':4,'c':3}
y = sorted(x.items(), key=lambda x: x[0], reverse=True)
print(y)
# 输出:
[('c', 3), ('b', 4), ('a', 1)]
# 这个时候y不是字典,我们再调用dict()函数转换成字典
y = dict(y)
print(y)
# 输出:
{'c': 3, 'b': 4, 'a': 1}
这就成功的排序了!!!
解释:reverse=True则按从大到小排序,为False则从小到大。
2、按值排序:
# 对字典x排序
x = {'a':1,'b':4,'c':3}
y = sorted(x.items(), key=lambda x: x[1], reverse=True)
print(y)
# 输出:
[('b', 4), ('c', 3), ('a', 1)]
# 这个时候y不是字典,我们再调用dict()函数转换成字典
y = dict(y)
print(y)
# 输出:
{'b': 4, 'c': 3, 'a': 1}