{"id":"25e43eac8aa72beb","repo":"pydantic/pydantic","slug":"cls-name-expected-dict-not-obj-class","errorCode":null,"errorMessage":"{cls.__name__} expected dict not {obj.__class__.__name__}","messagePattern":"(.+?) expected dict not (.+?)","errorType":"validation","errorClass":"ValidationError","httpStatus":null,"severity":"error","filePath":"pydantic/v1/main.py","lineNumber":548,"sourceCode":"    def _enforce_dict_if_root(cls, obj: Any) -> Any:\n        if cls.__custom_root_type__ and (\n            not (isinstance(obj, dict) and obj.keys() == {ROOT_KEY})\n            and not (isinstance(obj, BaseModel) and obj.__fields__.keys() == {ROOT_KEY})\n            or cls.__fields__[ROOT_KEY].shape in MAPPING_LIKE_SHAPES\n        ):\n            return {ROOT_KEY: obj}\n        else:\n            return obj\n\n    @classmethod\n    def parse_obj(cls: Type['Model'], obj: Any) -> 'Model':\n        obj = cls._enforce_dict_if_root(obj)\n        if not isinstance(obj, dict):\n            try:\n                obj = dict(obj)\n            except (TypeError, ValueError) as e:\n                exc = TypeError(f'{cls.__name__} expected dict not {obj.__class__.__name__}')\n                raise ValidationError([ErrorWrapper(exc, loc=ROOT_KEY)], cls) from e\n        return cls(**obj)\n\n    @classmethod\n    def parse_raw(\n        cls: Type['Model'],\n        b: StrBytes,\n        *,\n        content_type: str = None,\n        encoding: str = 'utf8',\n        proto: Protocol = None,\n        allow_pickle: bool = False,\n    ) -> 'Model':\n        try:\n            obj = load_str_bytes(\n                b,\n                proto=proto,\n                content_type=content_type,\n                encoding=encoding,","sourceCodeStart":530,"sourceCodeEnd":566,"githubUrl":"https://github.com/pydantic/pydantic/blob/2e5f0e2b4218de31709f1cf9c5bc61ea97a68835/pydantic/v1/main.py#L530-L566","documentation":"Raised by BaseModel.parse_obj (main.py:548) when the passed object is not a dict and cannot be converted via dict(obj) (the conversion raises TypeError or ValueError). parse_obj expects a mapping of field name -> value; non-mapping inputs that are not dict-convertible (e.g. a bare int, str, or a non-iterable object) produce this wrapped ValidationError.","triggerScenarios":"Calling Model.parse_obj(some_int), Model.parse_obj('string'), or parse_obj on a list of non-pair items. For custom-root (__root__) models, _enforce_dict_if_root wraps scalars first, so this fires mainly for non-root models given non-dict input.","commonSituations":"Passing a JSON-decoded value of the wrong shape, passing an ORM object to parse_obj instead of from_orm, or feeding a scalar where a dict was expected.","solutions":["Pass a dict (or a dict-convertible mapping) to parse_obj.","For ORM objects use Model.from_orm(obj) (with orm_mode=True).","For scalar/list root values, declare a __root__ field so the value is accepted directly.","Pre-validate the input shape before calling parse_obj."],"exampleFix":"// before\nm = M.parse_obj(42)  # raises 'expected dict not int'\n\n// after\nm = M.parse_obj({'value': 42})\n# or for a scalar root:\nclass M(BaseModel):\n    __root__: int\nm = M.parse_obj(42)","handlingStrategy":"type-guard","validationCode":"from typing import Mapping\n\ndef is_parseable_obj(obj) -> bool:\n    return isinstance(obj, Mapping) or _is_dict_convertible(obj)\n\ndef _is_dict_convertible(obj) -> bool:\n    try:\n        dict(obj)\n        return True\n    except (TypeError, ValueError):\n        return False\n\n# usage\nif not is_parseable_obj(payload):\n    raise TypeError(f'parse_obj expects a dict, got {type(payload).__name__}')\nMyModel.parse_obj(payload)","typeGuard":"from typing import Any, Mapping\n\ndef is_dict_like(value: Any) -> bool:\n    if isinstance(value, Mapping):\n        return True\n    try:\n        dict(value)\n        return True\n    except (TypeError, ValueError):\n        return False","tryCatchPattern":"from pydantic.v1 import ValidationError\n\ntry:\n    m = MyModel.parse_obj(payload)\nexcept ValidationError as e:\n    if 'expected dict not' in str(e):\n        m = MyModel.parse_obj({'value': payload})\n    else:\n        raise","preventionTips":["Always pass a dict (field name -> value) to parse_obj; for ORM objects use from_orm.","For scalar/list root values, declare a __root__ field.","Validate payload shape (isinstance(payload, dict)) before calling parse_obj."],"tags":["pydantic","parse-obj","validation","input-shape"],"analyzedSha":"2e5f0e2b4218de31709f1cf9c5bc61ea97a68835","analyzedAt":"2026-08-04T19:54:21.281Z","schemaVersion":2}