You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按指定键的数值从高到低对字典列表排序并以表格形式输出?

解决字典列表按售出房产数量排序后打印表格的问题

没问题,我帮你搞定这个排序的事儿!你当前的代码已经能正常生成表格,只需要在提取行数据之前,对data_list按照Properties Sold字段降序排序就可以实现你的需求。

修改后的完整代码

import tabulate
data_list = [
    {
        'Name': 'John Employee',
        'Employee ID': 12345,
        'Properties Sold': 5,
        'Commission': 2500,
        'Bonus to Commission': 0,
        'Total Commission': 2500
    },
    {
        'Name': 'Allie Employee',
        'Employee ID': 54321,
        'Properties Sold': 3,
        'Commission': 1500,
        'Bonus to Commission': 0,
        'Total Commission': 1500
    },
    {
        'Name': 'James Employee',
        'Employee ID': 23154,
        'Properties Sold': 7,
        'Commission': 3500,
        'Bonus to Commission': 525,
        'Total Commission': 4025
    }
]

# 按Properties Sold从高到低排序
sorted_data = sorted(data_list, key=lambda x: x['Properties Sold'], reverse=True)

header = sorted_data[0].keys()
rows = [x.values() for x in sorted_data]
print(tabulate.tabulate(rows, header))

关键说明

  • 使用Python内置的sorted()函数对字典列表排序:
    • key=lambda x: x['Properties Sold'] 指定排序依据是每个字典里的Properties Sold字段值
    • reverse=True 让排序结果是从高到低的降序(默认是升序)
  • 之后用排序后的sorted_data来提取表头和行数据,打印出来的表格就是你想要的排序结果了。

运行结果

Name            Employee ID  Properties Sold  Commission  Bonus to Commission  Total Commission
--------------  -------------  -----------------  ------------  ---------------------  ------------------
James Employee  23154         7                 3500          525                    4025
John Employee   12345         5                 2500          0                      2500
Allie Employee  54321         3                 1500          0                      1500

内容的提问来源于stack exchange,提问作者Zyan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 16:02:31