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

如何用TypedDict定义固定键为指定类型、其余键为统一类型的字典?

实现固定键类型+任意其余键类型的字典定义

要实现你需要的「指定固定键类型,其余任意新增键均为另一类型」的字典类型,有两种可行方案,适配不同Python版本:

方案1:兼容Python 3.8+(依赖MyPy支持)

通过TypedDict定义必填固定键,再与Mapping类型做交集,以此约束其余键值的类型:

from typing import TypedDict, Mapping
from typing_extensions import TypeAlias

# 定义必须存在的固定键及其类型
class BaseMovie(TypedDict):
    name: str

# 组合类型:必须包含name:str,其余键必须是str类型、值必须是int类型
Movie: TypeAlias = BaseMovie & Mapping[str, int]

# 合法示例:符合类型约束
movie: Movie = {'name': 'Blade Runner', 'year': 1982, 'nr_of_pancakes_in_movie': 42}

# 非法示例:nr_of_pancakes_in_movie的值不是int,会被MyPy报错
movie: Movie = {'name': 'Blade Runner', 'year': 1982, 'nr_of_pancakes_in_movie': "seven"}

方案2:Python 3.11+ 或使用typing_extensions

利用TypedDict的__extra_items__特性,可以直接在TypedDict类中声明其余任意键的类型:

from typing_extensions import TypedDict

class Movie(TypedDict):
    name: str
    # 声明任意额外键为str类型,对应值为int类型
    __extra_items__: str, int

# 合法示例
movie: Movie = {'name': 'Blade Runner', 'year': 1982, 'nr_of_pancakes_in_movie': 42}

# 非法示例:值类型不符合约束
movie: Movie = {'name': 'Blade Runner', 'year': 1982, 'nr_of_pancakes_in_movie': "seven"}

针对你的图集合场景的示例

结合你提到的NetworkX图类型需求,以下是适配的代码:

兼容版本方案

from typing import TypedDict, Mapping
import networkx as nx
from typing_extensions import TypeAlias

class BaseGraphSet(TypedDict):
    input: nx.Graph

# 组合类型:必须包含input:Graph,其余键对应值必须是DiGraph
GraphCollection: TypeAlias = BaseGraphSet & Mapping[str, nx.DiGraph]

# 合法示例
graphs: GraphCollection = {
    'input': nx.Graph(),
    'processed_graph_1': nx.DiGraph(),
    'processed_graph_2': nx.DiGraph()
}

# 非法示例:processed_graph_2的类型不符合要求,会被MyPy检测报错
graphs: GraphCollection = {
    'input': nx.Graph(),
    'processed_graph_1': nx.DiGraph(),
    'processed_graph_2': nx.Graph()
}

Python 3.11+ 方案

from typing_extensions import TypedDict
import networkx as nx

class GraphCollection(TypedDict):
    input: nx.Graph
    __extra_items__: str, nx.DiGraph

# 合法示例
graphs: GraphCollection = {
    'input': nx.Graph(),
    'processed_graph_1': nx.DiGraph(),
    'processed_graph_2': nx.DiGraph()
}

内容的提问来源于stack exchange,提问作者a.t.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 19:40:57