Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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'.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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')]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading