I have the following list of dictionaries:
lines = [
{
"attribute": [
{
"hello": "world"
},
{
"number": "2.2"
},
{
"this": "that"
}
],
"subline": [
{
"attribute": [
{
"number": "1"
}
]
},
{
"attribute": [
{
"number": "0"
}
]
},
{
"attribute": [
{
"number": "5"
}
]
}
]
},
{
"attribute": [
{
"number": "0.2"
}
],
"subline": []
},
{
"attribute": [],
"subline": [
{
"attribute": [
{
"number": "20.2"
}
]
},
{
"attribute": [
{
"number": "1"
},
{
"data": "15"
}
]
}
]
}
]
I would like to sort the list based on the value of the string "number" inside the attribute list inside the list of dictionaries.
Additionally, sort the subline list based on the same criteria (attribute number inside the subline list of dictionaries).
Sometimes the attribute "number" does not exist and sometimes the "subline" list might be empty.
The desired result would be:
lines = [
{
"attribute": [
{
"number": "0.2"
}
],
"subline": []
},
{
"attribute": [
{
"hello": "world"
},
{
"number": "2.2"
},
{
"this": "that"
}
],
"subline": [
{
"attribute": [
{
"number": "0"
}
]
},
{
"attribute": [
{
"number": "1"
}
]
},
{
"attribute": [
{
"number": "5"
}
]
}
]
},
{
"attribute": [],
"subline": [
{
"attribute": [
{
"number": "1"
},
{
"data": "15"
}
]
},
{
"attribute": [
{
"number": "20.2"
}
]
}
]
}
]
EDIT:
Here is how I have solved it:
lines = [{'attribute': [{'hello': 'world'}, {'number': '2.2'}, {'this': 'that'}], 'subline': [{'attribute': [{'number': '1'}]}, {'attribute': [{'number': '0'}]}, {'attribute': [{'number': '5'}]}]}, {'attribute': [{'number': '0.2'}], 'subline': []}, {'attribute': [], 'subline': [{'attribute': [{'number': '20.2'}]}, {'attribute': [{'number': '1'}, {'data': '15'}]}]}]
def getAttributeNumber(lineObject):
try:
if isinstance(lineObject.get("subline", []), list):
if len(lineObject.get("subline", [])) > 0:
lineObject.get("subline", []).sort(key=lambda o: getAttributeNumber(o))
if isinstance(lineObject.get("attribute", []), list):
for attr in lineObject.get("attribute", []):
if isinstance(attr.get("number"), str):
return attr.get("number")
return "A"
except Exception:
return "A"
lines.sort(key=lambda o: getAttributeNumber(o))
What's the most straightforward and perhaps the fastest way to achieve this?