Dictionary是一个标准的Python数据结构,以成对的形式存储元素。 key:value对。为了从字典中访问一个单独的项目,我们把键的名字放在方括号内 [].但是如果我们使用小括号(),我们会收到"TypeError: 'dict' object is not callable"。
在本指南中,我们将详细讨论"dict 对象不可调用 "的错误,并了解为什么 Python 会引发这个错误。我们还将通过一个你可能遇到这个错误的常见案例。在这个错误解决教程的最后,你将对Python程序中为什么会出现这个错误以及如何解决它有一个完整的概念。
Python错误--TypeError: 'dict'对象不可调用
Python Dictionary是一个可变的数据结构,它的数据类型是dict。它遵循方括号的语法来访问单个元素。
例子
students = {"Student1":"Rohan", "Student2":"Rahul", "Student3": "Akash"}
#access student
print(
但是如果我们使用小括号 ()而不是方括号 []我们将收到一个错误。
错误示例
students = {"Student1":"Rohan", "Student2":"Rahul", "Student3": "Akash"}
#access student
print(
错误声明
这个错误声明有两个部分"TypeError "和"'dict'对象不可调用"
类型错误是异常类型,告诉我们我们正在对一个Python数据对象进行一些无效的操作。在上面的例子中,我们收到这个异常是因为我们不能使用小括号来访问字典元素。
'dict'对象是不可调用的意味着我们正试图以函数或方法的形式调用一个 dictionary 对象。在 Python 中,函数和方法是可调用的对象,当我们要调用它们的名字时,我们在它们的后面加上小括号 **()**放在它们的名字后面,当我们想调用它们时。
但是 dictionary 不是一个函数或方法,当我们把括号放在 dictionary 名称后面时,Python 会抛出一个错误。
常见的例子情况
现在让我们讨论一个例子,你可能在你的 Python 代码中遇到这个错误。
假设我们有一个字典human ,其中包含一些关于人类的信息,我们需要在控制台面板上打印所有这些信息。
例子
#dictionary
human = {"family":"Hominidae",
"class": "Mammalia",
"species": "Homosapiens",
"kingdom": "Animalia",
"average speed": "13km/h",
"bite force": "70 pounds per square inch"
}
#print the details
for key in human:
print(key, "->",
输出
Traceback (most recent call last):
File "main.py", line 12, in
print(key, "->", human(key))
TypeError: 'dict' object is not callable
破解错误
在上面的例子中,我们得到的是TypeError: 'dict' object is not callable ,因为我们使用了 ()括号来访问字典中的数据值 human.
解决方法
要解决上面的例子,我们需要用[]括号替换()括号,同时我们用key访问字典的值。
#dictionary
human = {"family":"Hominidae",
"class": "Mammalia",
"species": "Homosapiens",
"kingdom": "Animalia",
"average speed": "13km/h",
"bite force": "70 pounds per square inch"
}
#print the details
for key in human:
print(key, "->",
输出
family -> Hominidae
class -> Mammalia
species -> Homosapiens
kingdom -> Animalia
average speed -> 13km/h
bite force -> 70 pounds per square inch
现在我们的代码运行成功,没有错误。
总结
当我们使用()括号来获取一个字典元素时,Python 程序中出现了"TypeError: 'dict' object is not callable "错误。为了调试这个错误,我们需要确保我们是用方括号 [] 来访问单个元素。