Dict object is not callable как исправить

On Career Karma, learn about the Python TypeError: ‘dict’ object is not callable, how the error works, and how to solve the error.

Items in a Python dictionary must be called using the indexing syntax. This means you must follow a dictionary with square brackets and the key of the item you want to access. If you try to use curly brackets, Python will return a “TypeError: ‘dict’ object is not callable” error.

In this guide, we talk about this error and why it is raised. We walk through an example of this error in action so you can learn how to solve it in your code.

Get offers and scholarships from top coding schools illustration

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Access exclusive scholarships and prep courses

Select your interest

First name

Last name

Email

Phone number

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

TypeError: ‘dict’ object is not callable

Dictionaries are iterable objects. This means that you can access items individually from inside a dictionary.

To access an item in a dictionary, you need to use indexing syntax. Here’s an example of indexing syntax in Python:

dictionary = {"key1": "value1"}
print(dictionary["key1"])

Run our code. “value” is returned. The value associated with the key “key1” is “value1”.

If we try to access an item from our dictionary using curly brackets, we encounter an error. This is because curly brackets are used to denote function calls in Python.

When Python sees a pair or curly brackets, it thinks you are trying to execute a function.

An Example Scenario

Here, we create a program that prints out all the values in a dictionary to the console. This dictionary contains information about a type of bird, the Starling.

Start by declaring a dictionary:

starling = {
	"name": "Starling",
	"Scientific_name": "Sturnus Vulgaris",
	"conservation_status_uk": "Red",
	"food": "Invertebrates and fruit"
}

This dictionary has four keys and four values. Let’s use print() statements to print each value from our dictionary to the console:

print("Name: " + starling("name"))
print("Scientific Name: " + starling("scientific_name"))
print("UK Conservation Status: " + starling("conservation_status_uk"))
print("What They Eat: " + starling("food")) 

This code should print out the values of “name”, “scientific_name”, “conservation_status_uk”, and “food” to the console. Run our code and see what happens:

Traceback (most recent call last):
  File "main.py", line 8, in <module>
	print("Name: " + starling("name"))
TypeError: 'dict' object is not callable

Our code returns an error.

This is because we are incorrectly accessing items from our dictionary. Dictionary items must be accessed using indexing syntax. In our code above, we’ve tried to use curly brackets to access items in our dictionary.

The Solution

To solve this error, we need to make sure we use square brackets to access items in our dictionary. Every time we access an item from the ‘starling” dictionary, we should use this syntax:

Use this syntax in our main program:

print("Name: " + starling["name"])
print("Scientific Name: " + starling["scientific_name"])
print("UK Conservation Status: " + starling["conservation_status_uk"])
print("What They Eat: " + starling["food"])

Our code now functions successfully:

Name: Starling
Scientific Name: Sturnus Vulgaris
UK Conservation Status: Red
What They Eat: Invertebrates and fruit

Instead of using curly brackets to access items in our dictionary, we have used square brackets. Square brackets indicate to Python that we want to access items from an iterable object. Curly brackets, on the other hand, indicate a function call.

Conclusion

The “TypeError: ‘dict’ object is not callable” error is raised when you try to use curly brackets to access items from inside a dictionary. To solve this error, make sure you use the proper square bracket syntax when you try to access a dictionary item.

Now you have all the knowledge you need to fix this error in your Python code!

A Python dictionary is a collection of data values stored in key-value pairs. To access items in a dictionary, you must use the indexing syntax of square brackets [] with the index position. If you use parentheses, you will raise the “TypeError: ‘dict’ object is not callable”.

This tutorial will describe the error and why it occurs. We will explore an example scenario of this error and go through how to solve it.


Table of contents

  • TypeError: ‘dict’ object is not callable
  • Example: Accessing Elements of a Dictionary
    • Solution
  • Summary

TypeError: ‘dict’ object is not callable

Python dictionary is a mutable data structure, meaning we can change the object’s internal state. Dictionaries are iterable objects, which means you can access items individually from inside the dictionary. Accessing an item from a dictionary follows the syntax of using square brackets with the index position. You must specify the appropriate key to access the value you want. If you use an unhashable type to access a dictionary, for example, a slice, you will raise the TypeError: unhashable type: ‘slice’. Let’s look at an example of accessing a dictionary:

pizzas = {

"name1": "margherita",

"name2": "pepperoni",

"name2": "four cheeses"

}
# Access pizza name

print(pizzas["name1"])
margherita

When we run our code, we print the value associated with the key “key1”.

TypeError tells us that we are trying to perform an illegal operation on a Python data object. Specifically, we cannot use parentheses to access dictionary elements. The part “‘dict’ object is not callable” tells us that we are trying to call a dictionary object as if it were a function or method. In Python, functions and methods are callable objects, they have the __call__ method, and you put parentheses after the callable object name to call it. Python dictionary is not a function or method, making calling a dictionary an illegal operation.

Example: Accessing Elements of a Dictionary

Let’s create a program that prints out the values of a dictionary to the console. The dictionary contains information about a type of fundamental particle, the muon.

We will start by declaring a dictionary for the muon data.

# Declare dictionary for muon particle

muon = {

   "name":"Muon",

   "charge":"-1",

   "mass":"105.7",

   "spin":"1/2"

}

The dictionary has four keys and four values. We can use the print() function to print each value to the console.

# Print values for each key in dictionary

print(f'Particle name is: {muon("name")}')

print(f'Particle charge is: {muon("charge")}')

print(f'Particle mass is : {muon("mass")} MeV')

print(f'Particle spin is: {muon("spin")}')

If we run the code, we get the following output:

TypeError                                 Traceback (most recent call last)
1 print(f'Particle name is: {muon("name")}')

TypeError: 'dict' object is not callable

We raise the error because we are not accessing the items with the correct syntax. In the above code, we used parentheses to access items in the dictionary.

Solution

To solve this error, we must replace the parentheses with square brackets to access the items in the muon dictionary.

# Print values for each key in dictionary

print(f'Particle name is: {muon["name"]}')

print(f'Particle charge is: {muon["charge"]}')

print(f'Particle mass is : {muon["mass"]} MeV')

print(f'Particle spin is: {muon["spin"]}')

When we run the code, we will get the following output:

Particle name is: Muon

Particle charge is: -1

Particle mass is : 105.7 MeV

Particle spin is: 1/2

Our code runs successfully and prints four aspects of the muon particle. Instead of using parentheses (), we used square brackets [].

We can also use items() to iterate over the dictionary as follows:

# Iterate over key-value pairs using items()

for key, value in muon.items():

   print(muon[key])

In the above code, we are iterating key-value pairs using items() and printing the value associated with each key. When we run the code, we will get the following output:

Muon

-1

105.7

1/2

Summary

Congratulations on reading to the end of this tutorial. The Python error “TypeError: ‘dict’ object is not callable” occurs when we try to call a dictionary like a function, and the Python dictionary is not a callable object. This error happens when we try to use parentheses instead of square brackets to access items inside a dictionary. You must use square brackets with the key name to access a dictionary item to solve this error.

For further reading on the “not callable” Python TypeError, you can read the following articles:

  • How to Solve Python TypeError: ‘nonetype’ object is not callable
  • How to Solve TypeError: ‘str’ object is not callable

To learn more about using dictionaries go to the article: Python How to Add to Dictionary.

Go to the Python online courses page to learn more about coding in Python for data science and machine learning.

Have fun and happy researching!

Why is the dict object is not callable error happeningThe dict object is not callable error usually occurs when you are looking to access items in a Python dictionary. This article will walk you through the coding mistakes that cause its occurrence. We will also discuss the solutions that can effectively fix those mistakes and make the coding process easier.

Contents

  • Why Is Dict Object Is Not Callable Error Happening?
    • – Calling a Dictionary as a Function
    • – Same Function and Variable Names
    • – Same Class Property and Class Method
    • – Usage of Curly Brackets
    • – Overriding the Built-in Dict() Function
  • How to Fix Not Callable Dict Object Issue
    • – Replacing Parentheses With Square Brackets
    • – Renaming Function and Variable Names
    • – Renaming Class Property and Class Method
    • The output of this implementation is:
    • – Using Indexing Syntax
    • – Renaming the Dictionary
  • Conclusion

Why Is Dict Object Is Not Callable Error Happening?

The dict’ object is not callable python json error can occur in Python due to one out of three reasons. The major reason involves an implementation in which a dictionary is called as if it is a function. The other possible reasons include the usage of curly brackets and overriding the built-in dict() function.

– Calling a Dictionary as a Function

This is a major reason for the occurrence of the error because it involves the most common mistake made by users. It happens due to the usage of parenthesis in an attempt to access a key in the dictionary. The following is a simple code example that leads to the Python typeerror and, as a result, its key cannot be accessed:

example_dict = {‘month’: ‘March’, ‘date’: 23}
# usage of parenthesis in the following lines
print (example_dict (‘month’))
print (example_dict (‘date’))

– Same Function and Variable Names

Consider the following code example that gives the dict’ object is not callable pandas error as the name of its variable and function are same:

def example():
return ‘A good day to you.’
# shadow function
example = {‘month’: ‘March’, ‘date’: 16}
# this gives the error
print (example())

In this example, the function is said to be shadowed by the ‘example’ variable due to their same names. As a result, its implementation results in calling that variable instead of the function.

– Same Class Property and Class Method

In some other cases, it is possible that the “dict’ object is not callable Django” error occurs due to a class property and a class method that have the same names. The following code example shows how that can happen:

class Event():
def __init__(self, address):
# method hidden by the attribute
self.address = address
# same name as class variable
def address(self):
return self.address
eve = Event({‘country’: ‘USA’, ‘city’: ‘Chicago’})
# this gives the error
print(eve.address())

In this example, the names of the attribute and method are the same for the “Event” class. This causes the attribute to hide that method and results in the occurrence of the dict’ object is not callable flask error. The attempt to call that method on an instance of the “Event” class is unsuccessful.

– Usage of Curly Brackets

The usage of curly brackets to call items in a dictionary can also cause the dict’ object is not callable zip error in Python. This is because their usage corresponds to the denoting of function calls instead of items.

Therefore, the presence of a pair of curly brackets signifies to the Python compiler that the implementation is aimed at the execution of a function. It means that their usage in an attempt to access an item from a dictionary leads to the occurrence of the error.

This code example involves the usage of curly brackets to print out every value in a dictionary. The items possess information about a ‘Civic’ car with curly brackets used along with the values of the dictionary.

The implementation is initiated with the declaration of the dictionary and the code example shows that it has four values and four keys. After this, all of those values are printed from that dictionary with the usage of print() statements to the console:

car = {
“name”: “Civic”,
“company_name”: “Honda”,
“fuel_consumption_average”: “30”,
“year”: “2016”
}
print (“Name: ” + car (“name”))
print (“Company Name: ” + car (“company_name”))
print (“Fuel Consumption Average: ” + car (“fuel_consumption_average”))
print (“Year of Manufacuring: ” + car (“year”))

The intended output should print out all the values involved in that dictionary that include “name”, “company_name”, “fuel_consumption_average” and “year”. However, the output of this implementation is:

Traceback (most recent call last):
File “HelloWorld.py”, line 7, in <module>
print (“Name: ” + car (“name”))
TypeError: ‘dict’ object is not callable

This implementation results in the error as the items are being incorrectly accessed from the dictionary. Curly brackets are used to access them, which is detected by the Python compiler and prompts the error.

– Overriding the Built-in Dict() Function

The error can also occur if the dict() function is overridden by the dictionary. A dictionary can override if it is declared with the same name (dict) as that of the function. The following is a code example that shows how an overridden dict() function can result in the error:

dict = {‘month’: ‘March’, ‘date’: 16}
print (dict (month =’March’, date = 16))

How to Fix Not Callable Dict Object Issue

The error caused by calling a dictionary as a function can be solved with the replacement of parentheses with square brackets.

The usage of curly brackets can be switched with an indexing syntax to fix the occurrence of the error. Moreover, renaming the dictionary can prevent it from overriding the built-in dict() function.

– Replacing Parentheses With Square Brackets

Accessing a key in a dictionary requires the usage of square brackets. To prevent the “typeerror: ‘dict’ object is not callable pytorch”, it is important that they are used like this:

my_dict [‘my_key’]. The code example mentioned in the reason above simply contains parentheses instead of square brackets.

Therefore, its implementation results in the error while accessing the key in the relevant dictionary. The code example below is a correction in which square brackets are used so that it is successfully implemented:

example_dict = {‘month’: ‘March’, ‘date’: 23}
# usage of square brackets in the following lines
print (example_dict [‘month’])
print (example_dict [‘date’])

The output of this implementation is:

The removal of parentheses essentially signifies the assignment of the dictionary to a variable. In this case, a class or a function is not assigned to the variable; therefore, the names of the variable or function must be different.

– Renaming Function and Variable Names

The typeerror ‘dict’ object is not callable multiprocessing occurring in the code example above can be simply solved by renaming either the function or the variable. Here is how you can do that:

def example():
return ‘A good day to you.’
# shadow function
myexample = {‘month’: ‘March’, ‘date’: 16}
# this gives the error
print (example())

The output of this implementation is:

– Renaming Class Property and Class Method

The “dict’ object is not callable jupyter notebook” error occurring in the code example above can be simply solved by renaming the class method. As a result, it can be called without any issues in the code. Here is how that can be done:

class Event():
def __init__(self, address):
# method hidden by the attributed
self.address = address
# same name as class variable
def get_address(self):
return self.address
eve = Event({‘country’: ‘USA’, ‘city’: ‘Chicago’})
print(eve.get_address())

The output of this implementation is:

{‘country’: ‘USA’, ‘city’: ‘Chicago’}

– Using Indexing Syntax

Switching from curly brackets requires the usage of an indexing syntax so that dictionary items can be accessed. It means that the indexing syntax can be used to call dictionary items in Python. As a result, the dictionary has to be followed by square brackets and a key of the item that has to be accessed.

Since dictionaries are iterable objects, items can be individually accessed from inside them. The indexing syntax comes in handy whenever an item has to be accessed in a dictionary. The syntax is like this where “value” is returned with “value1” being the value that is associated with the “key1” key:

dictionary = {“key1” : “value1”}
print (dictionary [“key1”])

This is important as square brackets correspond to indications for Python regarding the access of items from an iterable ‘dict’ object. Whereas, the indications from curly brackets correspond to a function call. With this, the following implementation solves the above code example of switching curly brackets:

car = {
“name”: “Civic”,
“company_name”: “Honda”,
“fuel_consumption_average”: “30”,
“year”: “2016”
}
print (“Name: ” + car [“name”])
print (“Company Name: ” + car [“company_name”])
print (“Fuel Consumption Average: ” + car [“fuel_consumption_average”])
print (“Year of Manufacturing: ” + car [“year”])

The output of this implementation is:

Name: Civic
Company Name: Honda
Fuel Consumption Average: 30
Year of Manufacturing: 2016

– Renaming the Dictionary

The error caused by the dictionary overriding the built-in dict() function can be solved by the technique of renaming. The dictionary name can be changed so that it does not override the function due to their same names. After that, the script can be restarted so that the implementation gives a successful output:

month_date = {‘month’: ‘March’, ‘date’: 16}
print (dict (month=’March’, age=16))

The output of this implementation is:

{‘month’: ‘March’, ‘age’: 16}

Conclusion

This article examined certain mistakes made in the code that become reasons for the error and also illuminated the necessary solutions for them. The following is a selection of the vital points:How to solve the dict object is not callable error

  • A dictionary called a function causes the error as it uses parenthesis to access a key in that dictionary.
  • The usage of curly brackets denotes function calls instead of items and results in error.
  • The built-in dict() function can be overridden by a dictionary if both of them have the same name.
  • Square brackets have to be used to access a key in a dictionary and prevent the error in Python.
  • The usage of an indexing syntax enables the access and calling of the items in a dictionary.

These solutions are bound to overcome the mistakes made that cause the error.

  • Author
  • Recent Posts

Position is Everything

Position Is Everything: Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL.

Position is Everything

Dictionary is a standard Python data structure that stores the elements in the form of


key:value


pairs. To access an individual item from the dictionary we put the key name inside a square bracket


[]


. But if we use the parenthesis


()


we will receive the

«TypeError: ‘dict’ object is not callable»

.

In this guide, we will discuss the

«dict object is not callable»

error in detail and learn why Python raises it. We will also walk through a common case scenario where you may encounter this error.

By the end of this error solution tutorial, you will have a complete idea of why this error raises in a Python program and how to solve it.

Python Dictionary is a mutable data structure, and it has a data type of


dict

.

It follows the syntax of the square bracket to access an individual element.


Example

students = {"Student1":"Rohan", "Student2":"Rahul", "Student3": "Akash"}

#access student
print(students["Student1"])    # Rohan

But if we use parenthesis


()


instead of the square bracket


[]


we will receive an error.


Error Example

students = {"Student1":"Rohan", "Student2":"Rahul", "Student3": "Akash"}

#access student
print(students("Student1"))   # TypeError: 'dict' object is not callable


Error Statement

This error statement has two parts

«TypeError»

and »

‘dict’ object is not callable»



TypeError


is the Exception Type telling us that we are performing some invalid operation on a Python data object.

In the above example, we are receiving this exception because we can not use parenthesis to access dictionary elements.


‘dict’ object is not callable


means we are trying to call a dictionary object as a function or method.

In Python functions and methods are callable objects, we put the parenthesis


()


after their name when we want to call them. But the dictionary is not a function or method, and when we put the parenthesis after the dictionary name Python throws an error.


Common Example Scenario

Now let’s discuss an example where you may encounter this error in your Python code. Let’s say we have a dictionary

human

that contains some information about the human species and we need to print all that information on the console panel.


Example

#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, "->", human(key))   #error


Output

Traceback (most recent call last):
  File "main.py", line 12, in 
    print(key, "->", human(key))
TypeError: 'dict' object is not callable


Break the Error

In the above example we are getting the

TypeError: 'dict' object is not callable

because we have used the


()


brackets to access the data value from the dictionary


human


.


Solution

To solve the above example, we need to replace the () brackets with [] brackets, while we are accessing the dictionary value using 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, "->", human[key]) # solved


Output

family -> Hominidae
class -> Mammalia
species -> Homosapiens
kingdom -> Animalia
average speed -> 13km/h
bite force -> 70 pounds per square inch

Now our code runs successfully with no error.


Conclusion

The Error

«TypeError: ‘dict’ object is not callable»

error raises in a Python program when we use the () brackets to get a dictionary element. To debug this error we need to make sure that we are using the square brackets [] to access the individual element.

If you are receiving this error in your Python program and could not solve it. You can share your code in the comment section, we will try to help you in debugging.


People are also reading:

  • Python Uppercase: A Complete Guide

  • Play sounds in Python

  • Make a Game With Python

  • Enumerate In Python

  • Flat List in Python

  • Python 3.10 Switch Case

  • CubicWeb In Python

  • Python Pickup Module

  • Tornado in Python

  • What you Can Do with Python?

I’m new to Python. I am getting the error TypeError:dict object is not callable. I haven’t used dictionary anywhere in my code.

def new_map(*arg1, **func): 
    result = []
    for x in arg1:
        result.append(func(x))
    return result

I tried calling this function as follows:

new_map([-10], func=abs)

But when I run it, I am getting the above error.

halfer's user avatar

halfer

19.7k17 gold badges95 silver badges183 bronze badges

asked Jun 29, 2018 at 11:05

Shsa's user avatar

The ** prefix says that all of the keyword arguments to your function should be grouped into a dict called func. So func is a dict and func(x) is an attempt to call the dict and fails with the error given.

answered Jun 29, 2018 at 11:08

Duncan's user avatar

DuncanDuncan

90k11 gold badges120 silver badges155 bronze badges

Seems like you are using arbitrary arguments when they are not required. You can simply define your function with arguments arg1 and func:

def new_map(arg1, func):
    result = []
    for x in arg1:
        result.append(func(x))
    return result

res = new_map([-10], abs)

print(res)

[10]

For detailed guidance on how to use * or ** operators with function arguments see the following posts:

  • *args and **kwargs?
  • What does ** (double star/asterisk) and * (star/asterisk) do for
    parameters?.

answered Jun 29, 2018 at 11:07

jpp's user avatar

jppjpp

155k33 gold badges271 silver badges330 bronze badges

6

You have used a dictionary by mistake. When you defined new_map(*arg1, **func), the func variable gathers the named parameter given during the function call. If func is supposed to be a function, put it as first argument, without * or **

answered Jun 29, 2018 at 11:08

blue_note's user avatar

blue_noteblue_note

26.8k8 gold badges65 silver badges84 bronze badges

func is a dictionary in your program. If you want to access value of it then you should use [] not (). Like:

def new_map(*arg1, **func): 
    result = []
    for x in arg1:
        result.append(func[x]) #use [], not ()
    return result

If func is a function to your program then you should write:

def new_map(*arg1, func): 
    result = []
    for x in arg1:
        result.append(func(x)) #use [], not ()
    return result

answered Jun 29, 2018 at 11:09

Taohidul Islam's user avatar

Taohidul IslamTaohidul Islam

5,1783 gold badges25 silver badges38 bronze badges

Or a simple list comprehension:

def new_map(arg1, func):
    return [func(i) for i in arg1]

out = new_map([-10], func=abs)
print(out)

Output:

[10]

answered Jun 29, 2018 at 11:16

U13-Forward's user avatar

U13-ForwardU13-Forward

67.8k14 gold badges83 silver badges105 bronze badges

I’m new to Python. I am getting the error TypeError:dict object is not callable. I haven’t used dictionary anywhere in my code.

def new_map(*arg1, **func): 
    result = []
    for x in arg1:
        result.append(func(x))
    return result

I tried calling this function as follows:

new_map([-10], func=abs)

But when I run it, I am getting the above error.

halfer's user avatar

halfer

19.7k17 gold badges95 silver badges183 bronze badges

asked Jun 29, 2018 at 11:05

Shsa's user avatar

The ** prefix says that all of the keyword arguments to your function should be grouped into a dict called func. So func is a dict and func(x) is an attempt to call the dict and fails with the error given.

answered Jun 29, 2018 at 11:08

Duncan's user avatar

DuncanDuncan

90k11 gold badges120 silver badges155 bronze badges

Seems like you are using arbitrary arguments when they are not required. You can simply define your function with arguments arg1 and func:

def new_map(arg1, func):
    result = []
    for x in arg1:
        result.append(func(x))
    return result

res = new_map([-10], abs)

print(res)

[10]

For detailed guidance on how to use * or ** operators with function arguments see the following posts:

  • *args and **kwargs?
  • What does ** (double star/asterisk) and * (star/asterisk) do for
    parameters?.

answered Jun 29, 2018 at 11:07

jpp's user avatar

jppjpp

155k33 gold badges271 silver badges330 bronze badges

6

You have used a dictionary by mistake. When you defined new_map(*arg1, **func), the func variable gathers the named parameter given during the function call. If func is supposed to be a function, put it as first argument, without * or **

answered Jun 29, 2018 at 11:08

blue_note's user avatar

blue_noteblue_note

26.8k8 gold badges65 silver badges84 bronze badges

func is a dictionary in your program. If you want to access value of it then you should use [] not (). Like:

def new_map(*arg1, **func): 
    result = []
    for x in arg1:
        result.append(func[x]) #use [], not ()
    return result

If func is a function to your program then you should write:

def new_map(*arg1, func): 
    result = []
    for x in arg1:
        result.append(func(x)) #use [], not ()
    return result

answered Jun 29, 2018 at 11:09

Taohidul Islam's user avatar

Taohidul IslamTaohidul Islam

5,1783 gold badges25 silver badges38 bronze badges

Or a simple list comprehension:

def new_map(arg1, func):
    return [func(i) for i in arg1]

out = new_map([-10], func=abs)
print(out)

Output:

[10]

answered Jun 29, 2018 at 11:16

U13-Forward's user avatar

U13-ForwardU13-Forward

67.8k14 gold badges83 silver badges105 bronze badges

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.

Понравилась статья? Поделить с друзьями:
  • Dialog oscar ao 55 ошибка pa0
  • Diagnostics performance код события 100 как исправить windows 10
  • Diagnostic port locked seagate как исправить
  • Diagnostic performance код ошибки 100
  • Diagnostic error text