Typeerror dict object is not callable python что это
Перейти к содержимому

Typeerror dict object is not callable python что это

  • автор:

How to Solve Python TypeError: ‘dict’ object is not callable

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

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:

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.

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

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

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.

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

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:

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:

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:

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.

How to fix "‘dict’ object is not callable" in Python

Update: This post was originally published on my blog decodingweb.dev, where you can read the latest version for a �� user experience.

The “TypeError: ‘dict’ object is not callable” error occurs when you try to call a dictionary (dict object) as if it was a function! Based on some threads on Stack Overflow, the most common cause of this error is using () rather than [] when accessing a dictionary item.

Here’s what the error looks like:

Exit fullscreen mode

Calling a dictionary object as if it’s a callable isn’t what you’d do on purpose, though. It usually happens due to a wrong syntax (as mentioned above) or overriding a builtin (or user-defined) function name with a dictionary object.

Let’s explore the common causes and their solutions.

How to fix TypeError: ‘dict’ object is not callable?

This TypeError happens under various scenarios:

  1. Accessing a dictionary item by () rather than []
  2. Declaring a dictionary with a name that’s also the name of a function
  3. Calling a method that’s also the name of a property
  4. Calling a method decorated with @property

Accessing a dictionary item by () rather than [] : The most common cause of this TypeError is accessing a dictionary item by () instead of [] .

Based on Python semantics, any identifier followed by a () is a function call. In this case, since () follows a dictionary object, it’s like you’re trying to call the dictionary like it’s callable.

As a result, you’ll get the «TypeError: ‘dict’ object is not callable» error.

Exit fullscreen mode

This is how you’re supposed to access a dictionary value:

Exit fullscreen mode

Declaring a dictionary with a name that’s also the name of a function: A Python function is an object like any other built-in object, such as str , int , float , dict , list , etc.

All built-in functions are defined in the builtins module and assigned a global name for easier access. For instance, dict() builtin function refers to the __builtins__.dict() function.

That said, overriding a function’s global name (accidentally or on purpose) with any value (e.g., a dictionary) is technically possible.

In the following example, we’ve declared a variable named range containing some config data. In its following line, we use the range() function in a for loop:

Exit fullscreen mode

If you run the above code, Python will complain with this type error because we’ve already assigned the range global variable to our first dictionary.

We have two ways to fix the issue:

  1. Rename the variable range
  2. Explicitly access the range() function from the builtins module ( __bultins__.range )

The second approach isn’t recommended unless you’re developing a module. For instance, if you want to implement an open() function that wraps the built-in open() :

Exit fullscreen mode

In almost every other case, you should always avoid naming your variables as existing functions and methods. But if you’ve done so, renaming the variable would solve the issue.

So the above example could be fixed like this:

Exit fullscreen mode

This issue is common with function names you’re more likely to use as variable names. Functions such as vars, locals, list, dict, all, or even user-defined functions.

⚠️ Long story short, you should never use a function name (built-in or user-defined) for your variables!

Overriding functions (and calling them later on) is one of the most common causes of the «TypeError: ‘dict’ object is not callable» error. It’s similar to calling integer numbers as if they’re callables.

Now, let’s get to the less common mistakes that lead to this error.

Calling a method that’s also the name of a property: When you define a property in a class constructor, it’ll shadow any other attribute of the same name.

Exit fullscreen mode

In the above example, we have a property named isbn — a dictionary to keep ISBN 10 and ISBN 13 of the book. Further down, we defined a method, also named isbn .

However the property isbn shadows the method isbn() . As a result, any reference to isbn returns the property — a dict object — not the method. And if you try to call this dict object, you should expect the «TypeError: ‘dict’ object is not callable» error.

The name get_isbn sounds like a safer and more readable alternative:

Exit fullscreen mode

Calling a method decorated with @property decorator: The @property decorator turns a method into a “getter” for a read-only attribute of the same name. You need to access a getter method without parenthesis, otherwise you’ll get a TypeError.

Exit fullscreen mode

To fix it, you need to access the getter method without the parentheses:

Exit fullscreen mode

Alright, I think it does it! I hope this quick guide helped you fix your problem.

TypeError: 'dict' object is not callable

I’m trying to loop over elements of an input string, and get them from a dictionary. What am I doing wrong?

9 Answers 9

The syntax for accessing a dict given a key is number_map[int(x)] . number_map(int(x)) would actually be a function call but since number_map is not a callable, an exception is raised.

Access the dictionary with square brackets.

You need to use [] to access elements of a dictionary. Not ()

You get an element from a dict using these [] brackets, not these () .

Use square brackets to explore dictionaries.

You need to use:

Note the square brackets!

A more functional approach would be by using dict.get

One can observe that the conversion is a little clumsy, better would be to use the abstraction of function composition:

Obviously in Python 3 you would avoid the explicit conversion to a list . A more general approach for function composition in Python can be found here.

(Remark: I came here from the Design of Computer Programs Udacity class, to write:)

it’s number_map[int(x)] , you tried to actually call the map with one argument

Use Square Brackets: —> number_map[int(x)]

YÜCEL CAN DOĞAN's user avatar

    The Overflow Blog
Linked
Related
Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.6.8.43486

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

TypeError: ‘dict’ object is not callable in Python – Easy Solutions To Fix

TypeError: ‘dict’ object is not callable in Python

When working with the dictionary, we may encounter the TypeError: ‘dict’ object is not callable in Python error several times. To know how to fix this error, read to the end of this article.

Table of Contents

Specific cases causing the error “TypeError: ‘dict’ object is not callable” in Python and how to fix it?

The error occurs when you try to access the dictionary variable the same way we call a function. Continue reading to find out how to avoid this error.

Access a dictionary variable as if calling a function

The error will appear when you access the dictionary variable, like calling a function. See the code sample below to understand.

Output:

Parentheses in Python are used to call functions, not to access variables. Therefore, to avoid the TypeError: ‘dict’ object is not callable in Python when we run the program, we should distinguish between functions and variables. Just remove the parenthesis in line 11, and we solve the problem.

Output:

Access an element of the dictionary using parentheses

This error can also occurs when you use a key to access the dictionary, like when you call a function that takes one parameter. Like this:

Output:

To fix this error, similar to the above case, just remember when accessing an element in the dictionary, we use square brackets, and when calling a function, we use parentheses. So you just need to change the parentheses to square brackets, and the problem is solved.

Output:

Summary

As you have seen when reading through the article, the error “TypeError: ‘dict’ object is not callable” in Python is easy to make but also very easy to avoid. Furthermore, you will never face this error again if you practice and work a lot with Python. Thank you for reading!

Maybe you are interested:

Lopez

Hi, I’m Cora Lopez. I have a passion for teaching programming languages such as Python, Java, Php, Javascript … I’m creating the free python course online. I hope this helps you in your learning journey.

Name of the university: HCMUE
Major: IT
Programming Languages: HTML/CSS/Javascript, PHP/sql/laravel, Python, Java

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *