简体   繁体   中英

error python 'dict' object is not callable

Hi im trying to run this code and i get this error. Anybody can help?

mydict = {"name":"Peter", "age":29, "hasaandroid":True}
mydict["location"] = "NewZealand"
print(mydict)

sentence = 'Hello my name is {} and i am {} years old. I live in    {}.'.format(mydict('name'), mydict('age'), mydict('location'))

This last code gives me an error like this

> TypeError Traceback (most recent call
> last) ~\AppData\Local\Temp/ipykernel_12864/3967542089.py in <module>
> ----> 1 sentence = 'Hello my name is {} and i am {} years old. I live in {}.'.format(mydict('name'), mydict('age'), mydict('location'))
> 
> TypeError: 'dict' object is not callable

Change it to use square brackets, instead of parenthesis.

sentence = 'Hello my name is {} and i am {} years old. I live in    {}.'.format(mydict['name'], mydict['age'], mydict['location'])

Parenthesis ( and ) are used to call an object, like invoking it as a function. Instead, use [ and ] to index a variable.

For building these kinds of strings, you're best off using an f-string, rather than using .format() . Also note that you need to use square brackets [] to index into the dictionary, rather than using parentheses () :

f'Hello my name is {mydict["name"]} and i am {mydict["age"]} years old. I live in {mydict["location"]}.'

This outputs:

Hello my name is Peter and i am 29 years old. I live in NewZealand.

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