如何将字典列表排序为单个列表,其中包含许多列表,并在每个列表中排序所有已排序的字典?

问题描述 投票:0回答:1

如何将字典列表排序为一个包含多个列表的单个列表,并在每个单个列表中排序所有已排序的字典?

示例

[
  {
    "Day": "Giornata 29",
    "Matches": {
      "Home": "Egnatia",
      "Away": "Kukesi",
      "Times": "19.03. 15:00",
      "Championship": "CALCIO\nALBANIA Super League\n2023/2024"
    }
  },
  {
    "Day": "Giornata 29",
    "Matches": {
      "Home": "Egnatia",
      "Away": "Kukesi",
      "Times": "20.03. 16:09",
      "Championship": "CALCIO\nALBANIA Super League\n2023/2024"
    }
  },
  {
    "Day": "Giornata 41",
    "Matches": {
      "Home": "Lincoln",
      "Away": "Leyton Orient",
      "Times": "19.03. 16:00",
      "Championship": "CALCIO\nINGHILTERRA League One\n2023/2024"
    }
  },
  {
    "Day": "Giornata 30",
    "Matches": {
      "Home": "Napoli",
      "Away": "Atalanta",
      "Times": "30.03. 12:30",
      "Championship": "CALCIO\nITALIA Serie A\n2023/2024"
    }
  }
]

我期望这样的输出:

{
  "Giornata 29": {
    "CALCIO\nALBANIA Super League\n2023/2024": [
      {
        "Day": "Giornata 29",
        "Matches": {
          "Home": "Egnatia",
          "Away": "Kukesi",
          "Times": "19.03. 15:00",
          "Championship": "CALCIO\nALBANIA Super League\n2023/2024"
        }
      },
      {
        "Day": "Giornata 29",
        "Matches": {
          "Home": "Egnatia",
          "Away": "Kukesi",
          "Times": "19.03. 15:00",
          "Championship": "CALCIO\nALBANIA Super League\n2023/2024"
        }
      }
    ]
  },
  "Giornata 41": {
    "CALCIO\nINGHILTERRA League One\n2023/2024": [
      {
        "Day": "Giornata 41",
        "Matches": {
          "Home": "Lincoln",
          "Away": "Leyton Orient",
          "Times": "19.03. 16:00",
          "Championship": "CALCIO\nINGHILTERRA League One\n2023/2024"
        }
      }
    ]
  },
  "Giornata 30": {
    "CALCIO\nITALIA Serie A\n2023/2024": [
      {
        "Day": "Giornata 30",
        "Matches": {
          "Home": "Napoli",
          "Away": "Atalanta",
          "Times": "30.03. 12:30",
          "Championship": "CALCIO\nITALIA Serie A\n2023/2024"
        }
      }
    ]
  }
}

我期望许多列表按“日”和“冠军”排序,如何才能以最简单的方式完成?

json python-3.x
1个回答
0
投票

假设您输入的数据位于名为

data
的变量中,您可以执行此操作(在我对您的问题的评论中注明了警告 - 这会产生您 show 的示例输出,而不是您在 describe 中的内容问题的开头):

from collections import defaultdict

data = ...

sorted_data = defaultdict(list)
for item in data:
    sorted_data[item["Day"]].append(item)

如果你想要内部列表按

...["Matches"]["Championship"]
排序,你可以这样做:

from collections import defaultdict
from bisect import insort


sorted_data = defaultdict(list)
for item in data::
    insort(sorted_data[item["Day"]], item, key=lambda x: x["Matches"]["Championship"])
© www.soinside.com 2019 - 2024. All rights reserved.