Search code examples
pythonjsonsortingalphabetical

Sorting dictionary values in Python


I have a data structure as follow:

Clients= {
      "data": [
        {
          "nClients": 3
        },
        {
          "name": "cTest1",
          "roll_no": 1,
          "branch": "c"
        },
        {
          "name": "fTest3",
          "roll_no": 3,
          "branch": "it3"          
        },
        {
          "name": "aTest2",
          "roll_no": 2,
          "branch": "it2"
        }
      ]
    }

I am trying to sort it out by the key 'name' alphabetically to have a result like this:

Clients= {
      "data": [
        {
          "nClients": 3
        },
        {
          "name": "aTest2",
          "roll_no": 2,
          "branch": "it2"          
        },
        {
          "name": "cTest1",
          "roll_no": 1,
          "branch": "c"
        },
        {
          "name": "fTest3",
          "roll_no": 3,
          "branch": "it3"
        }
      ]
    }

I have been looking around using the function sort(), dump() ecc, but I cannot find the correct syntax for this operation. Any suggestion? Thank you!


Solution

  • What you want to sort is a list, which is a value inside a dict under the key 'data'.

    You can use the built-in function sorted, specifying a callback as key:

    Clients["data"] = sorted(Clients["data"], key=lambda x: x.get("name", ""))
    

    Or the list method sort, which works in place:

    Clients["data"].sort(key=lambda x: x.get("name", ""))
    

    Both will result in:

    {
        "data": [
            {"nClients": 3},
            {"name": "aTest2", "roll_no": 2, "branch": "it2"},
            {"name": "cTest1", "roll_no": 1, "branch": "c"},
            {"name": "fTest3", "roll_no": 3, "branch": "it3"},
        ]
    }