菜鸟IT的博客 >> Python
根据字典的键值进行排序 | 对字典进行排序
链接:https://www.cnblogs.com/kilometerwine/p/9712329.html#:~:text=python%20%E6%A0%B9%E6%8D%AE%E5%AD%97%E5%85%B8%E7%9A%84%E9%94%AE%E5%80%BC%E8%BF%9B%E8%A1%8C%E6%8E%92%E5%BA%8F%201%E3%80%81%E5%88%A9%E7%94%A8key%E6%8E%92%E5%BA%8F%20d%20%3D%20%7B%20%27d1%27%20%3A2%2C,in%20sorted%20%28d%29%3A%20print%20%28k%2Cd%20%5Bk%5D%29%20d1%202
1、利用key排序
d = {'d1':2, 'd2':4, 'd4':1,'d3':3,}
for k in sorted(d):
print(k,d[k])
d1 2
d2 4
d3 3
d4 1
2、利用value排序:__getitem__
d = {'d1':2, 'd2':4, 'd4':1,'d3':3,}
for k in sorted(d,key=d.__getitem__):
print(k,d[k])
d4 1
d1 2
d3 3
d2 4
反序:reverse=True
d = {'d1':2, 'd2':4, 'd4':1,'d3':3,}
for k in sorted(d,key=d.__getitem__,reverse=True):
print(k,d[k])
d2 4
d3 3
d1 2
d4 1
3、对dict_items进行排序
d = {'d1':2, 'd2':4, 'd4':1,'d3':3,}
res = sorted(d.items(),key=lambda d:d[1],reverse=True)
print(res)
[('d2', 4), ('d3', 3), ('d1', 2), ('d4', 1)]
菜鸟IT博客[2022.12.01-10:04] 访问:294