Dict object is not callable ошибка

A more functional approach would be by using dict.get

input_nums = [int(in_str) for in_str in input_str.split())
strikes = list(map(number_map.get, input_nums.split()))

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

def compose2(f, g):
    return lambda x: f(g(x))

strikes = list(map(compose2(number_map.get, int), input_str.split()))

Example:

list(map(compose2(number_map.get, int), ["1", "2", "7"]))
Out[29]: [-3, -2, None]

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:)

def word_score(word):
    "The sum of the individual letter point scores for this word."
    return sum(map(POINTS.get, word))

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.9k17 gold badges100 silver badges187 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

92.2k11 gold badges124 silver badges157 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

160k34 gold badges281 silver badges339 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

27.8k9 gold badges73 silver badges91 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,2463 gold badges26 silver badges39 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

69.3k14 gold badges90 silver badges114 bronze badges

A more functional approach would be by using dict.get

input_nums = [int(in_str) for in_str in input_str.split())
strikes = list(map(number_map.get, input_nums.split()))

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

def compose2(f, g):
    return lambda x: f(g(x))

strikes = list(map(compose2(number_map.get, int), input_str.split()))

Example:

list(map(compose2(number_map.get, int), ["1", "2", "7"]))
Out[29]: [-3, -2, None]

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:)

def word_score(word):
    "The sum of the individual letter point scores for this word."
    return sum(map(POINTS.get, word))

Cover image for 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. ~reza

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:

Traceback (most recent call last):
  File "/dwd/sandbox/test.py", line 5, in 
    print(book('title'))
          ^^^^^^^^^^^^^
TypeError: 'dict' object is not callable

Enter fullscreen mode

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.

book = {
    'title': 'Head First Python', 'price': 46.01}

 # ⛔ Raises: TypeError: ‘dict’ object is not callable
print(book('title'))

Enter fullscreen mode

Exit fullscreen mode

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

book = {
    'title': 'Head First Python', 'price': 46.01}

print(book['title'])
# Output: Head First Python

print(book.get('price'))
# Output: 46.01

Enter fullscreen mode

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:

# Creating dict object named range
range = {'start': 0, 'end': 200}
# ⚠️ The above line overrides the original value of range (the 'range' class)

 # ⛔ Raises: TypeError: ‘dict’ object is not callable
for item in range(10, 20):
    print(item)

Enter fullscreen mode

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():

# Custom open() function using the built-in open() internally
def open(filename):
     # ...
     __builtins__.open(filename, 'w', opener=opener)
     # ...

Enter fullscreen mode

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:

range_config = {'start': 0, 'end': 200}

for item in range(10, 20):
    print(item)

Enter fullscreen mode

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.

class Book:
    def __init__(self, title, isbn):
        self.title = title
        self.isbn = isbn

    def isbn(self):
        return self.isbn

isbn = { 'isbn10': '1492051292', 'isbn13': '978-1492051299' }
book = Book('Head First Python', isbn)

print(book.isbn())
# 👆 ⛔ Raises TypeError: 'dict' object is not callable

Enter fullscreen mode

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:

class Book:
    def __init__(self, title, isbn):
        self.title = title
        self.isbn = isbn

    def get_isbn(self):
        return self.isbn

isbn = { 'isbn10': '1492051292', 'isbn13': '978-1492051299' }
book = Book('Head First Python', isbn)

print(book.get_isbn())
# Output: {'isbn10': '1492051292', 'isbn13': '978-1492051299'}

Enter fullscreen mode

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.

class Book:
    def __init__(self, title, isbn):
        self._title = title
        self._isbn = isbn

    @property
    def isbn(self):
        return self._isbn

isbn = { 'isbn10': '1492051292', 'isbn13': '978-1492051299' }
book = Book('Head First Python', isbn)

print(book.isbn())
# 👆 ⛔ Raises TypeError: 'dict' object is not callable

Enter fullscreen mode

Exit fullscreen mode

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

class Book:
    def __init__(self, title, isbn):
        self._title = title
        self._isbn = isbn

    @property
    def isbn(self):
        return self._isbn

isbn = { 'isbn10': '1492051292', 'isbn13': '978-1492051299' }
book = Book('Head First Python', isbn)

print(book.isbn)
# Output: {'isbn10': '1492051292', 'isbn13': '978-1492051299'}

Enter fullscreen mode

Exit fullscreen mode

Problem solved!

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

Thanks for reading.

❤️ You might like:

  • TypeError: ‘tuple’ object is not callable in Python
  • TypeError: ‘list’ object is not callable in Python
  • TypeError: ‘str’ object is not callable in Python
  • TypeError: ‘float’ object is not callable in Python
  • TypeError: ‘int’ object is not callable in Python

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!

Понравилась статья? Поделить с друзьями:
  • Diablo 2 resurrected ошибка при установке
  • Df645 ошибка рено мастер 3 дизель
  • Diagbox код ошибки 4
  • Diablo 2 resurrected ошибка видеокарты
  • Df504 ошибка рено дастер акпп