how to sort a dict list into a single list with many lists inside it and within each single list all the sorted dicts?
Example
[
{
"Day": "Giornata 29",
"Matches": {
"Home": "Egnatia",
"Away": "Kukesi",
"Times": "19.03. 15:00",
"Championship": "CALCIOnALBANIA Super Leaguen2023/2024"
}
},
{
"Day": "Giornata 29",
"Matches": {
"Home": "Egnatia",
"Away": "Kukesi",
"Times": "20.03. 16:09",
"Championship": "CALCIOnALBANIA Super Leaguen2023/2024"
}
},
{
"Day": "Giornata 41",
"Matches": {
"Home": "Lincoln",
"Away": "Leyton Orient",
"Times": "19.03. 16:00",
"Championship": "CALCIOnINGHILTERRA League Onen2023/2024"
}
},
{
"Day": "Giornata 30",
"Matches": {
"Home": "Napoli",
"Away": "Atalanta",
"Times": "30.03. 12:30",
"Championship": "CALCIOnITALIA Serie An2023/2024"
}
}
]
I expect an output like this:
{
"Giornata 29": {
"CALCIOnALBANIA Super Leaguen2023/2024": [
{
"Day": "Giornata 29",
"Matches": {
"Home": "Egnatia",
"Away": "Kukesi",
"Times": "19.03. 15:00",
"Championship": "CALCIOnALBANIA Super Leaguen2023/2024"
}
},
{
"Day": "Giornata 29",
"Matches": {
"Home": "Egnatia",
"Away": "Kukesi",
"Times": "19.03. 15:00",
"Championship": "CALCIOnALBANIA Super Leaguen2023/2024"
}
}
]
},
"Giornata 41": {
"CALCIOnINGHILTERRA League Onen2023/2024": [
{
"Day": "Giornata 41",
"Matches": {
"Home": "Lincoln",
"Away": "Leyton Orient",
"Times": "19.03. 16:00",
"Championship": "CALCIOnINGHILTERRA League Onen2023/2024"
}
}
]
},
"Giornata 30": {
"CALCIOnITALIA Serie An2023/2024": [
{
"Day": "Giornata 30",
"Matches": {
"Home": "Napoli",
"Away": "Atalanta",
"Times": "30.03. 12:30",
"Championship": "CALCIOnITALIA Serie An2023/2024"
}
}
]
}
}
I expect many lists sorted by "Day" and "Championship", how can this be done in the simplest way possible?
2
Answers
Assuming that you input data is in a variable named
data
, you could do this (with the caveat noted in my comment on your question — this produces the sample output you show, not what you describe in the beginning of the question):If you want the inner list sorted by
...["Matches"]["Championship"]
, you could do this:If you want the results in a sorted manner, then you might want to sort your input data as a first step. Since dictionaries preserve insertion order you should be able to preserve your sort order when constructing you result.
I personally prefer
setdefault()
todefaultdict()
but they very similar things in the end.You can read more about
dict.setdefault()
Giving you: