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

sag*_*gar 1 python sorting dictionary

输入数据:

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
    }]
Run Code Online (Sandbox Code Playgroud)

输出必须按如下方式排序,按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},
        ],
    }
Run Code Online (Sandbox Code Playgroud)

什么是pythonic方法呢?

Mar*_*ers 5

你在分组 ; 对于一个collections.defaultdict()对象来说这是最简单的:

from collections import defaultdict

newresult = defaultdict(list)

for entry in result:
    job_id = entry.pop('job_id')
    newresult[job_id].append(entry)
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)