pythondictionaryfilterstartswith

Filtering dictionary elements by few initial values


I have the following data structure:

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

I am trying to figure out a function that filters out the names given few initial letters, for example myFunction('Ma') that would give:

{
 "name": "Mark",
 "roll_no": 1,
 "branch": "c"
 },
 {
  "name": "Mark",
  "roll_no": 2,
  "branch": "it2"
  }

I am trying this kind of syntax: [client for client in Clients['data'] if 'name' in client and Clients['name'].startswith('Ma')]. However, I get the following error: KeyError: 'name'.

What am I doing wrong?

Thank you!


Solution

  • Based on @Michael Cao's comment, this should work:

    [client for client in Clients['data'] if 'name' in client and client['name'].startswith('Ma')]