在Python中,字典的排序可以通过内置的`sorted`函数结合`key`参数来实现。以下是不同场景下的具体方法:
python
d = {'a': 3, 'c': 1, 'b': 2}
按键升序排列,返回有序字典
sorted_by_key = dict(sorted(d.items, key=lambda x: x[0]))
结果:{'a': 3, 'b': 2, 'c': 1}
按键降序排列
sorted_by_key_desc = dict(sorted(d.items, key=lambda x: x[0], reverse=True))
结果:{'c': 1, 'b': 2, 'a': 3}
python
按值升序排列
sorted_by_value = dict(sorted(d.items, key=lambda x: x[1]))
结果:{'c': 1, 'b': 2, 'a': 3}
按值降序排列
sorted_by_value_desc = dict(sorted(d.items, key=lambda x: x[1], reverse=True))
结果:{'a': 3, 'b': 2, 'c': 1}
python
d = {'a': 2, 'c': 1, 'b': 2}
sorted_complex = dict(sorted(d.items, key=lambda x: (x[1], x[0])))
结果:{'c': 1, 'a': 2, 'b': 2}
python
class Person:
def __init__(self, age):
self.age = age
d = {'Alice': Person(30), 'Bob': Person(25)}
sorted_by_age = dict(sorted(d.items, key=lambda x: x[1].age))
结果:{'Bob': <__main__.Person object>, 'Alice': <__main__.Person object>}
若只需排序后的键、值或键值对列表:
python
按键列表
keys_sorted = sorted(d.keys)
按值列表
values_sorted = sorted(d.values)
按键值元组列表
items_sorted = sorted(d.items, key=lambda x: x[1])
通过灵活使用`sorted`和`key`参数,可以实现字典的多种排序需求。
版权声明: 知妳网保留所有权利,部分内容为网络收集,如有侵权,请联系QQ793061840删除,添加请注明来意。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态