python 字典 按键排序
时间: 2023-11-17 10:59:51 浏览: 136
Python中的字典是一种无序的数据结构,但是我们可以通过对键(key)或值(value)进行排序来达到排序的目的。对字典按键进行排序可以使用sorted()函数,该函数默认按照键(key)从小到大排序。对字典按值进行排序也可以使用sorted()函数,需要使用lambda表达式指定按照值(value)进行排序。同时,我们还可以使用reverse参数来指定排序的顺序,True表示降序,False表示升序。
下面是一个示例代码:
```
dict_data = {'3': 11, '6': 9, '7': 6, '8': 2, '10': 5}
# 对字典按键进行排序(默认由小到大)
test_data_0 = sorted(dict_data.keys())
print(test_data_0) # [3, 6, 7, 8, 10]
# 对字典按值进行排序(默认由小到大)
test_data_1 = sorted(dict_data.items(), key=lambda x: x[1])
print(test_data_1) # [('8', 2), ('10', 5), ('7', 6), ('6', 9), ('3', 11)]
# 对字典按值进行排序(由大到小)
test_data_2 = sorted(dict_data.items(), key=lambda x: x[1], reverse=True)
print(test_data_2) # [('3', 11), ('6', 9), ('7', 6), ('10', 5), ('8', 2)]
```
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)