python 根据字典的键值进行排序

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)]

你可能感兴趣的:(Python)