阅读量:2
在Python中,可以使用sorted()函数和字典的items()方法对字典进行排序。以下是一些示例:
- 按键排序:
my_dict = {'one': 1, 'three': 3, 'five': 5, 'two': 2, 'four': 4}
# 按键排序
sorted_dict = dict(sorted(my_dict.items(), key=lambda x: x[0]))
print(sorted_dict)
输出:
{'five': 5, 'four': 4, 'one': 1, 'three': 3, 'two': 2}
- 按值排序:
my_dict = {'one': 1, 'three': 3, 'five': 5, 'two': 2, 'four': 4}
# 按值排序
sorted_dict = dict(sorted(my_dict.items(), key=lambda x: x[1]))
print(sorted_dict)
输出:
{'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}
- 按键和值排序:
my_dict = {'one': 1, 'three': 3, 'five': 5, 'two': 2, 'four': 4}
# 按键和值排序
sorted_dict = dict(sorted(my_dict.items(), key=lambda x: (x[0], x[1])))
print(sorted_dict)
输出:
{'five': 5, 'four': 4, 'one': 1, 'three': 3, 'two': 2}
注意:sorted()函数返回的是一个排序后的列表,而不是字典。为了将其转换为字典,我们使用了dict()构造函数。
以上就是关于“Python字典操作怎样实现排序”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm