Fixed - dict object is not callable error in Python
In this tutorial, we are going to learn how to fix the TypeError: ‘dict’ object is not callable in Python.
When we try to call a dictionary object as a function using parenthesis ()
, we will get the “TypeError: ‘dict’ object is not callable” error in Python
Here is an example of how the error occurs:
car_dict = {"brand": "Ford", "year": 1964}
# using parenthesis for accessing data
print(car_dict("brand"))
Output:
Traceback (most recent call last):
File "main.py", line 12, in <module>
print(car_dict("brand")) # using parenthesis
TypeError: 'dict' object is not callable
In the example above , we are getting the error because we are using the parenthesis ()
to access the items of a dictionary instead of square brackets []
.
To fix the error, use the square brackets []
syntax to access the items from a dictionary.
Here is an example:
car_dict = {"brand": "Ford", "year": 1964}
print(car_dict["brand"]) # Ford
Note: The dict is an object data type in Python.
Another common cause of error is using the built-in dict()
function as a variable name.
Here is an example:
# overiding the built-in dict function
dict = {"brand": "Ford", "year": 1964}
# creating new dict using dict() function
new_user = dict(name = 'John', id = 99)
print(new_user)
To fix the error, change the variable name to some other name and re-run your code.
# not-overiding the built-in dict function
car_dict = {"brand": "Ford", "year": 1964}
new_user = dict(name = 'John', id = 99)
print(new_user)
Conclusion
The “dict” object is not callable error occurs, when we try to call a dictionary object as a function. To fix the error always use the square brackets []
to access the items of a dictonary
eg: car_dict["brand"]
and do not use the dict
built-in keyword as a variable name because it is reserved for dict()
function in python.