Search code examples
pythonlist-comprehensionnested-loops

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.

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)