簡體   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