如何在 python 中为具有不同类型作为值的字典添加类型声明

问题描述 投票:0回答:3

我有一本字典如下

my_dict = {
   "key_1": "value_1",
   "key_2": {
       "key_1": True,
           "key_2": 1200
       }
   "key_3": True,
}

在我的课堂上

@dataclass
class TestClass:
    my_dict: typing.Dict[{str, str}, {str, typing.Dict[{str, bool}, {str, int}]}]

以上声明不正确。

如果我想为 my_dict 添加类型,它应该是什么以及如何编写结构,因为我有不同的类型作为值?

python python-3.x typing
3个回答
4
投票

您想使用

Union
作为字典的值:

from typing import Dict, Union

@dataclass
class TestClass:
    my_dict: Dict[str, Union[str, bool, int]]

联合通知类型检查器字典中的值必须是

str
s、
bool
s 或
int
s。获取值时,您需要使用
isinstance
来确定如何处理值:

if isinstance(self.my_dict['a'], str):
    return self.my_dict['a'].encode('utf-8')
else isinstance(self.my_dict['a'], bool):
    return not self.my_dict['a']
else:
    return self.my_dict['a'] / 10

如果您知道某个键将包含特定类型,则可以使用

cast
:

来避免类型检查器的抱怨
from typing import cast

value = cast(bool, self.my_dict['some_bool'])

1
投票

我会刺一下它。因此,值的类型看起来非常独特并且很容易在运行时确定。访问字典数据并根据其类型对其执行某些操作的代码可以在 if/elif/else 块中使用 instanceof()

def some_method(self, key):
    val = self.my_dict[key]
    if isinstance(val, str): # fixed from instanceof to isinstance...
        print val
    elif isinstance(val, dict):
        print "it was a dictionary"
    else:
        print "Guess it must have been an int or bool."

或者你可以像这样测试类型:if type(val) is str: dosomething()


0
投票

Python 3.8 起,我们有

TypedDict
可以很好地解决您的需求:

from dataclasses import dataclass
from typing import TypedDict

class NestedDictType(TypedDict):
    key_1: bool
    key_2: int

class TopLevelDictType(TypedDict):
    key_1: str
    key_2: NestedDictType
    key_3: bool

@dataclass
class TestClass:
    my_dict: TopLevelDictType
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.