Sort Array object python

This code will help to sort any custom list object in ascending or descending order

accuracy=[
        {
            "Alg": "DecisionTree",
            "val": 90
        },
        {
            "Alg": "GradientBoosting",
            "val": 60
        },
        {
            "Alg": "LinearRegression",
            "val": 95
        },
        {
            "Alg": "LogisticRegression",
            "val": 96
        }
    ]

ascending=sorted(accuracy, key = lambda i: float(i['val']))
print(ascending)
desc=sorted(accuracy, key = lambda i: float(i['val']),reverse=True)
print(desc)
Output

[{'Alg': 'GradientBoosting', 'val': 60}, {'Alg': 'DecisionTree', 'val': 90}, {'Alg': 'LinearRegression', 'val': 95}, {'Alg': 'LogisticRegression', 'val': 96}]
[{'Alg': 'LogisticRegression', 'val': 96}, {'Alg': 'LinearRegression', 'val': 95}, {'Alg': 'DecisionTree', 'val': 90}, {'Alg': 'GradientBoosting', 'val': 60}]

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.