如何为具有不同类型的字典添加类型声明作为 python 中的值
How to add a typing declaration for a dict with different types as values in python
我有一个字典如下
my_dict = {
"key_1": "value_1",
"key_2": {
"key_1": True,
"key_2": 1200
}
"key_3": True,
}
在我的 class
@dataclass
class TestClass:
my_dict: typing.Dict[{str, str}, {str, typing.Dict[{str, bool}, {str, int}]}]
以上声明不正确。
如果我想为 my_dict 添加类型,它应该是什么以及如何编写结构,因为我有不同的类型作为值?
我来试试吧。因此,值的类型看起来非常不同并且很容易在运行时确定。访问字典数据并根据其类型对其执行某些操作的代码可以在 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."
或者您可以像这样测试类型:如果 type(val) 是 str: dosomething()
您想使用 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'])
我有一个字典如下
my_dict = {
"key_1": "value_1",
"key_2": {
"key_1": True,
"key_2": 1200
}
"key_3": True,
}
在我的 class
@dataclass
class TestClass:
my_dict: typing.Dict[{str, str}, {str, typing.Dict[{str, bool}, {str, int}]}]
以上声明不正确。
如果我想为 my_dict 添加类型,它应该是什么以及如何编写结构,因为我有不同的类型作为值?
我来试试吧。因此,值的类型看起来非常不同并且很容易在运行时确定。访问字典数据并根据其类型对其执行某些操作的代码可以在 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."
或者您可以像这样测试类型:如果 type(val) 是 str: dosomething()
您想使用 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'])