Skip to main content
 首页 » 编程设计

python之如何在 python 中对字典列表进行排序

2025年05月04日14myhome

输入数据:

results= [ 
        { 
      "timestamp_datetime": "2014-03-31 18:10:00 UTC", 
      "job_id": 5, 
      "processor_utilization_percentage": 72 
    }, 
        { 
      "timestamp_datetime": "2014-03-31 18:20:00 UTC", 
      "job_id": 2, 
      "processor_utilization_percentage": 60 
    }, 
        { 
      "timestamp_datetime": "2014-03-30 18:20:00 UTC", 
      "job_id": 2, 
      "processor_utilization_percentage": 0 
    }] 

输出必须按如下方式排序,按 job_id 升序分组:

newresult = { 
    '2':[{ "timestamp_datetime": "2014-03-31 18:20:00 UTC", 
            "processor_utilization_percentage": 60}, 
 
          {"timestamp_datetime": "2014-03-30 18:20:00 UTC", 
          "processor_utilization_percentage": 0},] 
 
    '5':[{ 
          "timestamp_datetime": "2014-03-31 18:10:00 UTC", 
          "processor_utilization_percentage": 72}, 
        ], 
    } 

执行此操作的 pythonic 方法是什么?

请您参考如下方法:

你正在分组;这是最简单的 collections.defaultdict() object :

from collections import defaultdict 
 
newresult = defaultdict(list) 
 
for entry in result: 
    job_id = entry.pop('job_id') 
    newresult[job_id].append(entry) 

newresult 是一个字典,它们没有顺序;如果您需要按升序访问作业 ID,请在列出它们时对键进行排序:

for job_id in sorted(newresult): 
    # loops over the job ids in ascending order. 
    for job in newresult[job_id]: 
        # entries per job id