So I have something like this:
[
{
"arg1":
{"valueone" : 2, "valuetwo": 5"},
},
{
"arg2":
{"valueone" : 7, "valuetwo": 3"},
},
{
"arg3":
{"valueone" : 3, "valuetwo": 7"},
},
{
"arg4":
{"valueone" : 4, "valuetwo": 6"},
},
{
"arg5":
{"valueone" : 9, "valuetwo": 5"},
},
]
I want to sort them by their valueone
s. I have a knowledge of OrderedDict, however I got some troubles to do this.
An expected result would be:
[
{
"arg5":
{"valueone" : 9, "valuetwo": 5"},
},
{
"arg2":
{"valueone" : 7, "valuetwo": 3"},
},
{
"arg4":
{"valueone" : 4, "valuetwo": 6"},
},
{
"arg3":
{"valueone" : 3, "valuetwo": 7"},
},
{
"arg1":
{"valueone" : 2, "valuetwo": 5"},
},
]
Any helps would be appreciated.
You could use the key parameter of sorted combined with reverse=True
, for instance:
data = [
{"arg1": {"valueone": 2, "valuetwo": "5"}},
{"arg2": {"valueone": 7, "valuetwo": "3"}},
{"arg3": {"valueone": 3, "valuetwo": "7"}},
{"arg4": {"valueone": 4, "valuetwo": "6"}},
{"arg5": {"valueone": 9, "valuetwo": "5"}}
]
result = sorted(data, key=lambda x: next(x["valueone"] for x in x.values()), reverse=True)
print(result)
Output
[{'arg5': {'valuetwo': '5', 'valueone': 9}}, {'arg2': {'valuetwo': '3', 'valueone': 7}}, {'arg4': {'valuetwo': '6', 'valueone': 4}}, {'arg3': {'valuetwo': '7', 'valueone': 3}}, {'arg1': {'valuetwo': '5', 'valueone': 2}}]