Search code examples
pythondictionarylist-comprehension

List comprehension with list of dictionaries


Please see this JSON structure:

[
  {
    "name": "blabla1",
    "value": "1"
  },
  {
    "name": "blabla2",
    "value": "2"
  },
  {
    "name": "blabla3",
    "value": "3"
  }
]

And I have a simple class:

@dataclass
class Data:
    name: str = field(init=True)
    value: str = field(init=True)
    is_valid: bool = field(init=False, default=True)

And I want to read this file and create a list of this data class.

This is what I have tried:

v = ...

This v contains a list of dictionaries (3 according my example here)

data = [[(Data(name=k, value=v, is_valid=True)) for k, v in v.items()] for d in v]

The results here is a list of 7 Data types but for each item in this list I have another list of 2 items with Data type


Solution

  • ads the JSON file and returns a list of Data objects. Each object is created by passing the name and value fields from the corresponding dictionary in the JSON file. The is_valid field is set to True by default:

    import json
    
    @dataclass
    class Data:
        name: str
        value: str
        is_valid: bool = True
    
    def read_json_file(file_path: str) -> List[Data]:
        with open(file_path, 'r') as f:
            data = json.load(f)
        return [Data(d['name'], d['value']) for d in data]