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

List comprehension from JSON file with several items in list

I have some issues to read a nested data structure from .json file via list comprehension.

This is my file:

"persons": [
    {
      "A": [
        {
          "type": "type1",
          "value": "",
          "is_valid": true
        },
        {
          "type": "type1",
          "value": "",
          "is_valid": true
        }
      ]
    },
    {
      "B": [
        {
          "type": "type2",
          "value": "",
          "is_valid": true
        }
      ]
    },
    {
      "C": [
        {
          "type": "type3",
          "value": "",
          "is_valid": true
        },
        {
          "type": "type3",
          "value": "",
          "is_valid": false
        }
      ]
    }
  ]

I want to read all the "persons" fields and return a list of Person objects.

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

Currently this is my approach:

def get_all() -> list[Person]:
    persons = []
    for p in config['persons']:
        for key, values in p.items():
            for value in values:
                persons.append(Person(type=value['type'], name=f'{key}', value='{}'.format(value['value']), is_valid=value['is_valid']))
    return persons

I tried to convert it to a list comprehesion:

return [[(k, v) for k, v in d.items()] for d in config['persons']]

But it returns a list of lists.

My Person object has 4 fields:

name: str
type: str
value: str
is_valid: bool

>Solution :

To proceed with list comprehension use the following approach:

persons = [Person(name=k, **f)
           for d in config['persons'] for k, v in d.items() for f in v]

Note how field (dict) is unpacked **f (to fit the remaining object properties)

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