Python 如何判断变量是否是特定类型的字典?i、 e.dict(int,str)
我有一本字典-Python 如何判断变量是否是特定类型的字典?i、 e.dict(int,str),python,dictionary,types,isinstance,Python,Dictionary,Types,Isinstance,我有一本字典- d = dict( 0='a', 1='b', 2='c' ) 我如何判断d是否是(int,str)类型的dict 在C#中,它将类似于: d.GetType() == typeof(Dictionary<int, string>) from typing import Dict d: Dict[int, str] = { 0: 'a', 1: 'b', 2: 'c' } print(__annotations__['d']) d.G
d = dict(
0='a',
1='b',
2='c'
)
我如何判断d
是否是(int,str)
类型的dict
在C#中,它将类似于:
d.GetType() == typeof(Dictionary<int, string>)
from typing import Dict
d: Dict[int, str] = { 0: 'a', 1: 'b', 2: 'c' }
print(__annotations__['d'])
d.GetType()==typeof(字典)
在单个Python字典中,值可以是任意类型。键还有一个额外的要求,即它们必须是可散列的,但它们也可能涵盖多种类型
要检查字典中的键或值是否属于特定类型,可以迭代它们。例如:
values_all_str = all(isinstance(x, str) for x in d.values())
keys_all_int = all(isinstance(x, int) for x in d)
在单个Python字典中,值可以是任意类型。键还有一个额外的要求,即它们必须是可散列的,但它们也可能涵盖多种类型 要检查字典中的键或值是否属于特定类型,可以迭代它们。例如:
values_all_str = all(isinstance(x, str) for x in d.values())
keys_all_int = all(isinstance(x, int) for x in d)
Python字典没有类型。实际上,您必须检查每个键和值对。例如
all(isinstance(x, basestring) and isinstance(y, int) for x, y in d.items())
Python字典没有类型。实际上,您必须检查每个键和值对。例如
all(isinstance(x, basestring) and isinstance(y, int) for x, y in d.items())
如果您使用的是Python 3.7,则可以执行以下操作:
d.GetType() == typeof(Dictionary<int, string>)
from typing import Dict
d: Dict[int, str] = { 0: 'a', 1: 'b', 2: 'c' }
print(__annotations__['d'])
然后返回:typing.Dict[int,str]
有一个函数将来可能有用,但目前只知道以下类型的对象:
函数、方法、模块或类
还说要对此做些什么如果您使用的是Python 3.7,您可以执行以下操作:
d.GetType() == typeof(Dictionary<int, string>)
from typing import Dict
d: Dict[int, str] = { 0: 'a', 1: 'b', 2: 'c' }
print(__annotations__['d'])
然后返回:typing.Dict[int,str]
有一个函数将来可能有用,但目前只知道以下类型的对象:
函数、方法、模块或类
还说要对此做些什么字典没有特定的类型。您可以混合和匹配不同类型的键和值
d={0:'a','foo':1}
这不是定义python dicts的有效方法。如图所示,dicts是异构的,您必须检查每个项目以确保,例如[(type(k),type(v)]中的k,v。items()][/code>这不是您开始键入的方式。Python不关心它是否是特定类型,它关心它是否像特定类型一样工作。字典没有特定类型。您可以混合和匹配不同类型的键和值d={0:'a','foo':1}
这不是定义python dicts的有效方法。如图所示,dicts是异构的,您必须检查每个项目以确保,例如[(type(k),type(v)]中的k,v。items()][/code>这不是您开始键入的方式。Python不关心它是否是一个特定的类型,它关心它的行为是否像一个特定的类型。