Python如何对字典排序?使用sorted()函数
-
sorted(iterable,key,reverse)
iterable:是要排序的序列,表示可以迭代的对象,例如可以是dict.items()、dict.keys()等。
key:是一个函数,用来选取参与比较的元素,以什么规则或者标准来确定被排序对象的顺序,如以key的大小,或者value的大小。
reverse:用来指定排序是倒序还是顺序,reverse=True则是倒序。
2.
dict={6: 9, 10: 5, 3: 11, 8: 2, 7: 6}#字典dict
test_data_0=sorted(dict.keys())#1.对字典的所有key进行排序
print(test_data_0)#[3, 6, 7, 8, 10]
test_data_1=sorted(dict.items(), key=lambda x: x[0])#对字典(key,value)按照key的大小升序排列
print(test_data_1)#[(3, 11), (6, 9), (7, 6), (8, 2), (10, 5)]
test_data_2=sorted(dict.items(), key=lambda x: x[1])#对字典(key,value)按照value的大小升序排列
print(test_data_2)#[(8, 2), (10, 5), (7, 6), (6, 9), (3, 11)]
test_data_3=sorted(dict.items(), key=lambda x: x[1], reverse=True)##对字典(key,value)按照value的大小降序排列
print(test_data_3)#[(3, 11), (6, 9), (7, 6), (10, 5), (8, 2)]