Python dictionary type() 方法用于检索传递的变量的类型。如果传递的变量是字典,则它将返回字典类型。
字典是 Python 中的一种映射数据类型。由键及其相应值集合组成的数据类型称为映射类型。映射是可变对象,这意味着其状态在创建后可以修改。
语法
以下是 Python 字典 type() 方法的语法 -
type(dict)
参数
- dict − 这是字典。
返回值
此方法返回传递的变量的类型。
例以下示例显示了 Python dictionary type() 方法的用法。这里创建了一个字典 'dict'。然后使用 type() 方法检索字典中传递的变量的类型。
# creating a dictionary
dict = {'Name': 'Zara', 'Age': 7};
# printing the result
print ("Variable Type : %s" % type (dict))
当我们运行上述程序时,它会产生以下结果——
Variable Type : <class 'dict'>
例
在这里,我们正在创建一个空字典 'dict_1'。然后使用 type() 方法返回空字典的类型。
# Creating an empty dictionary
dict_1 = {};
res = type(dict_1)
# Printing the result
print ("The equivalent string is: ", res)
以下是上述代码的输出 -
The equivalent string is: <class 'dict'>
例
在以下示例中,我们将创建嵌套词典 'dict_1' 的列表。然后使用 type() 方法返回此字典的类型。
dict_1 = [{'Universe' : {'Planet' : 'Earth'}}]
print("The dictionary is: ", dict_1)
# using type() method
result = type(dict_1)
print("The equivalent string is: ", result)
上述代码的输出如下: −
The dictionary is: [{'Universe': {'Planet': 'Earth'}}]
The equivalent string is: <class 'list'>
The equivalent string is: <class 'list'>