python type_error ai_generated true

pydantic.errors.DictError: value is not a valid dict

ID: python/pydantic-dict-key-type

Also available as: JSON · Markdown · 中文
80%Fix Rate
83%Confidence
0Evidence
2024-04-05First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
2.x active

Root Cause

A field typed as Dict[str, int] receives a dict with non-string keys or non-int values, causing validation failure.

generic

中文

类型为 Dict[str, int] 的字段接收到键不是字符串或值不是整数的字典,导致验证失败。

Workarounds

  1. 90% success
    Convert keys to strings: {str(k): v for k, v in data.items()}
  2. 85% success
    Change type to Dict[str, Any] if flexible

Dead Ends

Common approaches that don't work:

  1. 80% fail

    Key type must be str, integer keys fail.

  2. 70% fail

    Value type must be int, float fails.