簡體   English   中英

錯誤 python 'dict' 對象不可調用

[英]error python 'dict' object is not callable

嗨,我正在嘗試運行此代碼,但出現此錯誤。 有人可以幫忙嗎?

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

最后的代碼給了我這樣的錯誤

> 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

將其更改為使用方括號,而不是括號。

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

括號( and )用於調用對象,就像將其作為函數調用一樣。 相反,使用[]來索引變量。

要構建這些類型的字符串,最好使用 f 字符串,而不是使用.format() 另請注意,您需要使用方括號[]來索引字典,而不是使用括號()

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

這輸出:

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