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

如何为Python字符串键嵌套字典结构添加正确类型提示?

为嵌套字典添加类型提示

你可以通过**dict[str, _Preferences](Python 3.9+)或者Dict[str, _Preferences]**(Python 3.8及以下)给外层的people字典添加类型提示,明确它的键为字符串类型,值是你定义的_Preferences字典类型。

完整代码示例

# Python 3.8及以下需导入Dict,3.9+可省略Dict,直接用内置的dict
from typing import TypedDict, Dict

class _Preferences(TypedDict):
    likes: str
    dislikes: str

# Python 3.9+ 推荐写法
people: dict[str, _Preferences] = { 
   "john" : {"likes": "apples", "dislikes": "oranges"},
   "aisha": {"likes": "kittens", "dislikes": "ravens"}
}

# Python 3.8及以下兼容写法
# people: Dict[str, _Preferences] = { 
#    "john" : {"likes": "apples", "dislikes": "oranges"},
#    "aisha": {"likes": "kittens", "dislikes": "ravens"}
# }

说明

  • 该类型提示会告知类型检查工具(如mypy、PyCharm):people的所有键都是字符串,每个键对应的值必须是包含likes和dislikes两个字符串字段的字典。
  • 后续访问people的元素时,编辑器或检查工具会自动补全字段,并对不符合类型的赋值或访问给出警告。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 12:30:55