Python 3.11:未知深度嵌套字典的类型提示如何编写?
未知深度嵌套字典的类型提示写法
在Python 3.11中,针对未知深度的字符串键嵌套字典(比如你生成的树结构,叶子为空白字典),可以通过递归类型别名来编写清晰的类型提示,具体方案如下:
方法一:使用递归类型别名(推荐)
先定义一个递归的类型别名,明确表示“键为字符串,值为同类型嵌套字典”——空字典本身就符合这个类型约束,不需要额外声明。
示例代码:
from __future__ import annotations # 定义递归类型别名,描述字符串键的嵌套字典 NestedDict = dict[str, NestedDict] source = [('a', 'b'), ('b', 'c'), ('d', 'e')] target = {'a': {'b': {'c': {}}}, 'd': {'e': {}}} def tree_form(source: list[tuple[str, str]]) -> NestedDict: tree = {} for parent, offspring in source: current = tree # 构建树结构的简化实现 if parent not in current: current[parent] = {} current = current[parent] current[offspring] = {} return tree
如果不想引入__future__ annotations,也可以用字符串字面量引用类型别名:
from typing import Dict NestedDict = Dict[str, 'NestedDict'] def tree_form(source: list[tuple[str, str]]) -> NestedDict: # 实现代码 pass
方法二:直接写递归类型(可读性较差)
如果不想定义类型别名,也可以直接在返回值位置写递归的类型提示,但可读性不如类型别名:
def tree_form(source: list[tuple[str, str]]) -> dict[str, 'dict[str, ...]']: # 实现代码 pass
需要注意的是,你的目标结构中,叶子节点的空字典完全符合dict[str, NestedDict]的类型定义,因为空字典没有键值对,不存在违反类型约束的情况,不需要额外添加| dict来声明。
内容的提问来源于stack exchange,提问作者eightlay
相关产品推荐
相关产品推荐

