繁体   English   中英

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

[英]How to sort a list of dictionaries in python?

输入数据:

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()对象

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

您可以使用itertools.groupbyresults按其job_id分组:

from itertools import groupby
new_results = {k: list(g) for k, g in groupby(results, key=lambda d: d["job_id"])}

结果是字典,即没有特定顺序。 如果要按升序迭代值,则可以执行以下操作:

for key in sorted(new_results):
    entries = new_results[key]
    # do something with entries

更新:正如Martijn指出的那样,这要求results列表按job_id排序(如您的示例所示),否则条目可能会丢失。

假设您确实不希望newresult中的job_id:

from collections import defaultdict
newresult = defaultdict(list)
for result in results:
    job_id = result['job_id']
    newresult[job_id].append( 
        {'timestamp_datetime':result['timestamp_datetime'],
         'processor_utilization_percentage':result['processor_utilization_percentage']}
        )
#print newresult

我真的没有找到一种通过字典理解来做到这一点的方法,但是我敢肯定,有人在做这种事情方面有更多的经验,可以将其付诸实践。 但是,这非常简单。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM