python type_error ai_generated true

pydantic.errors.DictError: 值不是有效的字典

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

ID: python/pydantic-dict-key-type

其他格式: JSON · Markdown 中文 · English
80%修复率
83%置信度
0证据数
2024-04-05首次发现

版本兼容性

版本状态引入弃用备注
2.x active

根因分析

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

English

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

generic

解决方案

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

无效尝试

常见但无效的做法:

  1. 80% 失败

    Key type must be str, integer keys fail.

  2. 70% 失败

    Value type must be int, float fails.