konradhalas / dacite

Simple creation of data classes from dictionaries.
MIT License
1.72k stars 106 forks source link

ValueError: dictionary update sequence element #0 has length 1; 2 is required #243

Closed rafaelfalcaro closed 1 year ago

rafaelfalcaro commented 1 year ago

Describe the bug I'm trying to create a class object of PLCProgram type from a dict, but this error is returned: "ValueError: dictionary update sequence element #0 has length 1; 2 is required"

To Reproduce Json file with dict:

{
  "plc_programs": [
    {
      "id": 0,
      "type": "iocstop",
      "cs_motors": {
        "1": [1, 2, 3],
        "2": [4, 5, 6, 7]
      },
      "motors": [10, 11, 12]
    },
    {
      "id": 1,
      "type": "iocstop",
      "cs_motors": {
        "2": [1, 2, 3]
      }
    }
  ]
}

The code:

from dacite import from_dict, Config
from dataclasses import dataclass
from enum import Enum
from typing import Optional
import json

class PLCProgramType(str, Enum):
    """Enumerate PLC Program types available."""
    IOCSTOP = "iocstop"

@dataclass
class PLCProgram:
    """PLC Program data structure."""
    id: int
    type: PLCProgramType
    cs_motors: Optional[list[dict]] = None
    motors: Optional[list[int]] = None

with open("data.json", "r", encoding="utf-8") as f:
        data = json.load(f)

plc_progs = []

for plc_prog in data["plc_programs"]:
  config = Config(type_hooks={PLCProgramType: PLCProgramType})
  plc_progs.append(from_dict(PLCProgram, plc_prog, config))

print(plc_progs)

Environment

rafaelfalcaro commented 1 year ago

I've found my error:

+ cs_motors: Optional[list[dict]] = None
- cs_motors: Optional[dict] = None

The opened issue is not a bug of dacite lib.