Python字典排序:按水果名称排序水果价格字典
Python字典排序:按水果名称排序水果价格字典
本文将介绍如何使用 Python 对字典进行排序,以一个包含五种水果每斤售价的字典 fruits 为例:python# 创建包含水果和价格的字典fruits = { 'watermelon': 16, 'Banana': 10, 'Pineapple': 15, 'Orange': 12, 'Apple': 18}
目标:
- 打印初始字典
fruits。2. 按水果名称对字典进行排序。
**代码实现:**python# 创建包含水果和价格的字典fruits = { 'watermelon': 16, 'Banana': 10, 'Pineapple': 15, 'Orange': 12, 'Apple': 18}
打印初始字典print('初始字典:')print(fruits)
按水果名称排序并打印sorted_fruits = dict(sorted(fruits.items(), key=lambda x: x[0]))print('
按水果名称排序后的字典:')print(sorted_fruits)
代码解释:
- 创建字典: 首先,我们创建一个名为
fruits的字典,包含五种水果及其对应的价格。2. 打印初始字典: 使用print(fruits)打印初始的字典内容。3. 排序: 使用sorted(fruits.items(), key=lambda x: x[0])对字典进行排序。 *fruits.items(): 返回字典的键值对列表。 *key=lambda x: x[0]: 使用lambda表达式指定按照键(水果名称)进行排序。4. 转换为字典: 使用dict()函数将排序后的结果转换回字典形式。5. 打印排序后的字典: 使用print(sorted_fruits)打印排序后的字典内容。
输出结果:
初始字典:{'watermelon': 16, 'Banana': 10, 'Pineapple': 15, 'Orange': 12, 'Apple': 18}
按水果名称排序后的字典:{'Apple': 18, 'Banana': 10, 'Orange': 12, 'Pineapple': 15, 'watermelon': 16}
总结:
通过以上代码,我们成功地按水果名称对字典进行了排序。sorted() 函数和 lambda 表达式的结合使用为 Python 字典排序提供了灵活而强大的功能。
原文地址: https://www.cveoy.top/t/topic/IMo 著作权归作者所有。请勿转载和采集!