You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何mypy对我的字典推导式报类型不兼容错误?

问题原因

mypy 会根据初始的load_result = {"load_code": "something"}自动推断其类型为dict[str, str](所有值均为字符串),但你通过update传入的字典推导式生成的是dict[str, list[float]],两者的 value 类型不兼容,因此触发类型错误。

解决方法

你需要显式指定load_result的类型,允许它同时容纳字符串和浮点列表两种值:

方法1:使用 Union 类型(Python 3.9 及之前)

from typing import Dict, Union, List

load_result: Dict[str, Union[str, List[float]]] = {"load_code": "something"}
load_result.update({
    quality_result.quality_code: [quality_result.quantity]
    for quality_result in random_quality_results()
})

方法2:使用联合类型语法(Python 3.10+)

Python 3.10 支持更简洁的联合类型写法:

load_result: dict[str, str | list[float]] = {"load_code": "something"}
load_result.update({
    quality_result.quality_code: [quality_result.quantity]
    for quality_result in random_quality_results()
})

方法3:放宽类型至 object(不推荐)

如果不需要严格的类型检查,可以将类型标注为dict[str, object],但这会丢失类型提示的优势:

load_result: dict[str, object] = {"load_code": "something"}

内容的提问来源于stack exchange,提问作者aarcas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 14:55:31