Python字典操作怎样实现排序

1028
2024/11/9 12:30:50
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Python中,可以使用sorted()函数和字典的items()方法对字典进行排序。以下是一些示例:

  1. 按键排序:
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}
  1. 按值排序:
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}
  1. 按键和值排序:
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()构造函数。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: python怎么查找字符第一次出现的位置