Table of Contents
ToggleWhat is a callable object ?
In simple terms any object that can be called using parentheses () is called a callable object. Similarly how we invoke a function. Callables include functions, methods, classes and objects that implement the special __call__() method.
In the blog we will learn how to solve typeerror : dict object is not callable.
Why Are Dictionaries Not Callable ?
Dictionaries are data structures and are not callable in Python because they are not designed to perform an action upon being invoked with parentheses. Primary function of a dictionary is to map keys to values using square brackets “ [ ] ” and not using parentheses.”( )” . If we try to call a dictionary as if it was a function Python raises a ‘dict’ object is not callable error.
Common Causes of the dict Object is Not Callable' Error
Using Parentheses Instead of Square Brackets
If we use Parentheses mistakenly to access values in the dictionary we get an error. If we see the code below , “number_map” is a dictionary and we are trying to loop over the dictionary to print the values. To access the values from the dictionary we are using parentheses which would give an error.
Python code
number_map = {1: 'One', 2: 'Two'} # Incorrectly trying to access the dictionary in a loop for num in [1, 2]: print(number_map(num)) # TypeError: 'dict' object is not callable
Output
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[1], line 4 2 # Incorrectly trying to access the dictionary in a loop 3 for num in [1, 2]: ----> 4 print(number_map(num)) # TypeError: 'dict' object is not callable TypeError: 'dict' object is not callable
Solution: We should always check that we are using square brackets instead of using parentheses to access dictionary values:
Python Code
number_map = {1: 'One', 2: 'Two'} for num in [1, 2]: print(number_map[num]) # Correct way
Output
One Two
Overwriting the Built-in dict Type
Another mistake new developers make is assigning a dictionary to a variable name that is already taken as a built-in Python function.
For example if you see in the below code variable is named as ‘dict’ and is used to store a dictionary. Then in the next line we are initializing a dictionary. This line throws an error as It causes a conflict. The conflict is due to Built-in dict type being overwritten by assigning a dictionary to the variable name dict.
Python Code
dict = {'a': 1, 'b': 2} my_dict = dict() # TypeError: 'dict' object is not callable -------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[3], line 3 1 dict = {'a': 1, 'b': 2} ----> 3 my_dict = dict() # TypeError: 'dict' object is not callable TypeError: 'dict' object is not callable
Solution:
We should always avoid using names that conflict with built-in types. Rename our variable to the point what they are storing makes always sense.
Python code
my_dict_var = {'a': 1, 'b': 2} my_dict = dict()
Misusing a Dictionary in a List Comprehension
The list comprehension code tries to get all the values of the dictionary. But the code will throw an error as we are using parenthese “()” to access the value.
Python code
my_dict = {'a': 1, 'b': 2} values = [my_dict(x) for x in my_dict.keys()] -------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[3], line 3 1 my_dict = {'a': 1, 'b': 2} ----> 3 values = [my_dict(x) for x in my_dict.keys()] Cell In[3], line 3 1 my_dict = {'a': 1, 'b': 2} ----> 3 values = [my_dict(x) for x in my_dict.keys()] TypeError: 'dict' object is not callable
Solution: If we replace parentheses with square brackets the code will work
Python code
values = [my_dict[x] for x in my_dict.keys()] print(values)
Function that Returns a Dictionary
The function name and dictionary name are the same in the below causing an error when the function is invoked.
Python code
def create_dict(): return {'x': 10, 'y': 20} # Redefining the function with a dictionary create_dict = {'a': 1} # Calling it as a function will raise the error result = create_dict()
output
-------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[6], line 8 5 create_dict = {'a': 1} 7 # Calling it as a function will raise the error ----> 8 result = create_dict() TypeError: 'dict' object is not callable
Solution: Using unique names for functions and variables will solve the problem
Python code
def create_new_dict(): return {'x': 10, 'y': 20}
Using a Dictionary in a Class Method
class MyClass: def __init__(self): self.my_dict = {'key': 'value'} def get_value(self, key): return self.my_dict(key) # TypeError: 'dict' object is not callable obj = MyClass() print(obj.get_value('key'))Output
-------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[7], line 9 6 return self.my_dict(key) # TypeError: 'dict' object is not callable 8 obj = MyClass() ----> 9 print(obj.get_value('key')) Cell In[7], line 6 5 def get_value(self, key): ----> 6 return self.my_dict(key) TypeError: 'dict' object is not callableSolution: Use square brackets to access dictionary keys: Python code
def get_value(self, key): return self.my_dict[key]
Using a Dictionary in Lambda Function
In the code a lambda function is incorrectly trying to access values in my_dict using parentheses
Python code
my_dict = {1: 'One', 2: 'Two'} # Creating a lambda that mistakenly tries to call the dictionary my_lambda = lambda x: my_dict(x) print(my_lambda(1))
Output
TypeError Traceback (most recent call last) Cell In[8], line 5 3 # Creating a lambda that mistakenly tries to call the dictionary 4 my_lambda = lambda x: my_dict(x) # TypeError: 'dict' object is not callable ----> 5 print(my_lambda(1)) Cell In[8], line 4 1 my_dict = {1: 'One', 2: 'Two'} 3 # Creating a lambda that mistakenly tries to call the dictionary ----> 4 my_lambda = lambda x: my_dict(x) # TypeError: 'dict' object is not callable 5 print(my_lambda(1)) TypeError: 'dict' object is not callable
Solution: We need to use square brackets to correctly access the dictionary:
my_lambda = lambda x: my_dict[x] # Correct way
Best Practices to Avoid dict Object is Not Callable' Errors
Use Descriptive and Unique Variable Names.
We should always avoid using names that are already used in built in function of python like ‘dict’ or ‘list’ to prevent name collisions. Using desciptive and unique name to variables helps us understand the code better.
Consistently Review Your Code for Function-Object Confusion
If you are developing a big application always modularize the code and create functions. Keep checking for misused parentheses for accessing the dictionary values.
Leverage Python IDEs and Linters for Early Detection
Modern Python IDEs already help us catch syntax errors and name conflicts by highlighting them in some way. They don’t let you run into mistakes. For this, we can use tools like PyCharm, VSCode, and Flake8.
Conclusion
The ‘dict’ object cannot be called error occurs when the developer tries to use the dictionary as a function. These errors are caused by syntax errors or variable names that conflict with built-in functions.
Follow the checklist to avoid the Error
- Always use square brackets [] to access dictionary items.
- Avoid overlapping built-in user names with variable names.
- Check your code regularly for callable-object confusion
Pingback: Solving the 'dict_keys' Object is Not Subscriptable Error in Python