简体   繁体   中英

TypeError in python which says that dict object is not callable

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.

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:

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.

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 **

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

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM