简体   繁体   English

错误 python 'dict' 对象不可调用

[英]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.括号( and )用于调用对象,就像将其作为函数调用一样。 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() .要构建这些类型的字符串,最好使用 f 字符串,而不是使用.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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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