在Python中,字典(dict)本身是无序的,但自Python 3.7版本起,字典会保留插入顺序。若需要对字典进行排序,可以通过以下方法实现:
python
d = {'b': 2, 'a': 1, 'c': 3}
sorted_by_key = dict(sorted(d.items, key=lambda x: x[0]))
结果:{'a': 1, 'b': 2, 'c': 3}
python
sorted_by_value = dict(sorted(d.items, key=lambda x: x[1]))
结果:{'a': 1, 'b': 2, 'c': 3}
添加 `reverse=True` 参数:
python
sorted_by_key_desc = dict(sorted(d.items, key=lambda x: x[0], reverse=True))
结果:{'c': 3, 'b': 2, 'a': 1}
例如,先按值排序,再按键排序:
python
sorted_multi = dict(sorted(d.items, key=lambda x: (x[1], x[0])))
对于Python 3.7之前的版本,可使用 `collections.OrderedDict` 保持顺序:
python
from collections import OrderedDict
sorted_ordered = OrderedDict(sorted(d.items, key=lambda x: x[0]))
python
scores = {'Alice': 90, 'Bob': 85, 'Charlie': 95}
sorted_scores = dict(sorted(scores.items, key=lambda x: x[1], reverse=True))
结果:{'Charlie': 95, 'Alice': 90, 'Bob': 85}
通过 `key` 和 `reverse` 参数控制排序规则。
版权声明: 知妳网保留所有权利,部分内容为网络收集,如有侵权,请联系QQ793061840删除,添加请注明来意。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态