Python 字典排序:按水果名称排序打印水果价格
以下是用 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('\n按水果名称排序后的字典:')
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 表达式来按照水果名称对字典进行排序。首先,通过 items() 方法获取字典中的键值对,并通过 key=lambda x: x[0] 指定按照键(水果名称)进行排序。最后,使用 dict() 函数将排序后的结果转换回字典形式。
原文地址: http://www.cveoy.top/t/topic/Jpu 著作权归作者所有。请勿转载和采集!