Python如何按字典quantity值排序水果并输出对应价格与数量
实现代码
你的字典为平行列表存储结构,需要先将各字段对应索引的元素绑定后再按quantity降序排序,完整实现如下:
my_dict = {'name': ['apple', 'orange', 'banana'], 'quantity': [20, 10, 30], 'price': [45, 50, 75]} # 1. 配对同索引的水果名、数量、价格,按数量降序排序 sorted_fruits = sorted(zip(my_dict['name'], my_dict['quantity'], my_dict['price']), key=lambda item: item[1], reverse=True) # 单独获取排序后的水果名称列表 sorted_names = [item[0] for item in sorted_fruits] print(sorted_names) # 输出:['banana', 'apple', 'orange'] # 2. 按要求格式输出 for i, (name, quantity, price) in enumerate(sorted_fruits): # 第一个水果前加>>>前缀,其余保持缩进 line_prefix = ">>> " if i == 0 else " " print(f"{line_prefix}{name}:") print(f" price: {price}") print(f" quantity: {quantity}") # 除最后一项外,其余项后加空行分隔 if i != len(sorted_fruits) - 1: print()
错误原因说明
你之前尝试的写法直接对my_dict.items()排序,实际处理的是字典的三个顶层键值对(即('name', 水果列表)、('quantity', 数量列表)、('price', 价格列表)这三个项),并没有把每个水果对应的数量、价格关联起来,所以无法得到预期结果。
内容的提问来源于stack exchange,提问作者Morello
相关产品推荐
相关产品推荐

