在Python中,字典本身是无序的(Python 3.7之前)或保持插入顺序(Python 3.7+),但可以通过内置函数`sorted`对字典的键值对进行排序。以下是常见的排序方法:
将字典按照键的字母顺序或数值大小排序:
python
d = {'a': 3, 'b': 1, 'c': 2}
按键升序排序,返回列表
sorted_by_key = sorted(d.items, key=lambda x: x[0])
print(sorted_by_key) 输出: [('a', 3), ('b', 1), ('c', 2)]
转换为有序字典(Python 3.7+)
sorted_dict = dict(sorted_by_key)
print(sorted_dict) 输出: {'a': 3, 'b': 1, 'c': 2}
将字典按照值的大小排序:
python
按值升序排序
sorted_by_value = sorted(d.items, key=lambda x: x[1])
print(sorted_by_value) 输出: [('b', 1), ('c', 2), ('a', 3)]
按值降序排序
sorted_by_value_desc = sorted(d.items, key=lambda x: x[1], reverse=True)
print(sorted_by_value_desc) 输出: [('a', 3), ('c', 2), ('b', 1)]
通过`operator.itemgetter`提高代码可读性和效率:
python
from operator import itemgetter
按键排序
sorted_by_key = sorted(d.items, key=itemgetter(0))
按值排序
sorted_by_value = sorted(d.items, key=itemgetter(1))
多级排序(例如先按值,再按键):
python
d = {'a': 2, 'b': 1, 'c': 2}
先按值升序,再按键升序
sorted_complex = sorted(d.items, key=lambda x: (x[1], x[0]))
print(sorted_complex) 输出: [('b', 1), ('a', 2), ('c', 2)]
使用`collections.OrderedDict`保持顺序:
python
from collections import OrderedDict
sorted_items = sorted(d.items, key=lambda x: x[1])
ordered_dict = OrderedDict(sorted_items)
print(ordered_dict) 输出: OrderedDict([('b', 1), ('c', 2), ('a', 3)])
`reverse=True`实现降序排序。
版权声明: 知妳网保留所有权利,部分内容为网络收集,如有侵权,请联系QQ793061840删除,添加请注明来意。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态