Sort dictionary by value

Sorting the recordset is very basic and frequently used requirement. Let’s assume that you have a dictionary as shown below and you want to sort the data by key “is_selected”.

resultSet = {
    "data": [
        {
            "id": 1,
            "title": "Focus",
            "slug": "focus",
            "is_selected": false
        },
        {
            "id": 3,
            "title": "Sleep",
            "slug": "sleep",
            "is_selected": false
        },
        {
            "id": 4,
            "title": "Patience",
            "slug": "patience",
            "is_selected": true
        },
        {
            "id": 6,
            "title": "Relaxed mind",
            "slug": "relaxed_mind",
            "is_selected": true
        },
        {
            "id": 5,
            "title": "Relaxed body",
            "slug": "relaxed_body",
            "is_selected": false
        }
    ]
}

You can sort this by following code:

sorted_by_is_selected = sorted(resultSet.data, key=lambda k: k['is_selected'], reverse=True)

Reverse True/False will use to set the sorting order Ascending/Descending respectively.

{
    "data": [
        {
            "id": 4,
            "title": "Patience",
            "slug": "patience",
            "is_selected": true
        },
        {
            "id": 6,
            "title": "Relaxed mind",
            "slug": "relaxed_mind",
            "is_selected": true
        },
        {
            "id": 1,
            "title": "Focus",
            "slug": "focus",
            "is_selected": false
        },
        {
            "id": 3,
            "title": "Sleep",
            "slug": "sleep",
            "is_selected": false
        },
        {
            "id": 5,
            "title": "Relaxed body",
            "slug": "relaxed_body",
            "is_selected": false
        }
    ]
}

 

Leave a Reply

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

Back to Top
Shares