In: Computer Science
lines = [ { "name": "student19",
"test1": "70",
"test2": "70",
"test3": "83",
"test4": "99",
"test5": "97"
},
{
"name": "student20",
"test1": "68",
"test2": "68",
"test3": "81",
"test4": "74",
"test5": "76"
},
{
"name": "student21",
"test1": "74",
"test2": "73",
"test3": "84",
"test4": "84",
"test5": "69"
},]
I need to sort the test3 only in descending order using python lambda function.
it should look like something like this:
l_func=lambda line: here goes the function
return output=sorted(lines, key=l_func)
thanks
So we need to sort this array of dicts acording to the test3 value only and in descending order, it means dicts with greater value of test3 will come first and dicts with least value of test3 will come last.
Have a look at the below code. I have put comments wherever required for better understanding.
lines = [ { "name": "student19",
"test1": "70",
"test2": "70",
"test3": "83",
"test4": "99",
"test5": "97"
},
{
"name": "student20",
"test1": "68",
"test2": "68",
"test3": "81",
"test4": "74",
"test5": "76"
},
{
"name": "student21",
"test1": "74",
"test2": "73",
"test3": "84",
"test4": "84",
"test5": "69"
},]
# This is the lambda function which will sort the array by test3 value
l_func = lambda x:x["test3"]
# since we need it in descending order, we will add an extra parameter of reverse and will set it to True
output=sorted(lines, key=l_func,reverse = True)
print(output)
Happy Learning!