Register Login

TypeError: ‘dict’ object is not callable

Updated Feb 17, 2020

TypeError: ‘dict’ object is not callable

In this article we will learn about the TypeError: ‘dict’ object is not callable.

This error is generated when we try to call a dictionary using invalid methods. As shown in the example below.

Example:

# Creating dictionary 'MyDict'
MyDict= {
'car' : 'Honda city',
'type': 'sedan',
'color' : 'Blue'
}

# Printing Dictionary
print(MyDict())

# Checking length of dictionary
print("length of the dictionary :",len(MyDict))

Output:

File "nterror.py", line 9, in <module>
print(MyDict( ))
TypeError: 'dict' object is not callable

In the above example, we can see that in line 9 of the code i.e print(MyDict()), we called our dictionary using parenthesis. And thus causing the error, “TypeError: 'dict' object is not callable”.

Now the question arises why we can’t call the dictionary using parenthesis ( )?

To understand this let us take the help of a ‘dir( )’ a built-in method. Which returns the list of all the functions/methods associated with the object.

TypeError: ‘dict’ object is not callable.

Example:

dir(MyDict)

Output: 
['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']

The output shows the list of all the functions associated with a dictionary object. To make an object callable the presence of a magic function(__call__) is a must.

We can see in the above output, the magic function (__call__) is not defined or is absent. The absence of this magic function is what made our dictionary uncallable. Thus the dictionary object can not be invoked using parenthesis( ).

TypeError: ‘dict’ object is not callable.    

Solution:

Do print(MyDict) instead of print(MyDict( )) in line 9 of the code.

# Creating dictionary 'MyDict'
MyDict= {
'car' : 'Honda city',
'type': 'sedan',
'color' : 'Blue'
}

# Printing Dictionary
print(MyDict)

# Checking length of dictionary
print("length of the dictionary :",len(MyDict))

Output:

{'car': 'Honda city', 'type': 'sedan', 'color': 'Blue'}
length of the dictionary : 3

TypeError: ‘dict’ object is not callable.


×