字典按照值或键进行排序
使用sorted函数进行排序
sorted(iterable,key,reverse)
sorted一共有iterable, key, reverse这三个参数;
参数 | 作用 |
---|---|
iterable | 可迭代对象 , 例如: dict.items()、dict.keys()等 |
key | 用来选取参与比较的元素, 例如确定是按照字典的键比较还是按照值进行比较 |
reverse | 用来指定排序是升序还是降序,reverse=true是降序,false时则是升序,默认时是升序 |
#初始化字典
a = { "b": 5, "c": 2,"a": 4, "d": 1}
- 1、对字典按键(key)进行排序
#对字典按键(key)进行排序(默认由小到大)
test_1=sorted(a.items(),key=lambda x:x[0])
#输出结果
print(test_1) # [('a', 4), ('b', 5), ('c', 2), ('d', 1)]
- 2、对字典按值(value)进行排序
#对字典按值(value)进行排序(默认由小到大)
test_2=sorted(a.items(),key=lambda x:x[1])
#输出结果
print(test_2) # [('d', 1), ('c', 2), ('a', 4), ('b', 5)]
其中key=lambda x:x[1]
简单理解为a.items
中有两个元素:
x[0]
表示按照第一元素进行排序
x[1]
表示按照第二个元素进行排序