I have translated a program from javascript to python 3.9 and I am only missing sorting the result, but I just can't get any further.
The list consists of dicts that has an id "components", which is itself a list.
recipe.components.sort((a, b) => (a.components ? 1 : 0) - (b.components ? 1 : 0))
If i understood the java code correctly, then all elements (a.components) that are an empty list should be at the beginning and all that have elements in their list should be at the end, but that's the small problem, because you can reverse it with .reverse()
anyway.
recipe.components = [{
"id": 123,
"components": [{"id": 1, "components": []}]
},
{
"id": 124,
"components": [{"id": 2, "components": []}, {"id": 3, "components": []}]
},
{
"id": 125,
"components": []
},
{
"id": 126,
"components": [{"id": 1, "components": []}]
}]
Does anyone know how to write this most elegantly in Python?
--- Edit ---
I solved it like this:
recipe["components"].sort(key=lambda a: 1 if a.get("components") else 0)