You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中使用变量的值而非其标识符访问字典对应内容

问题解决方法

你代码中的错误是因为Python的点号访问规则:使用dict.key的写法时,程序会将key视为固定的属性名称,而非动态变量,因此你的代码会尝试查找fruits字典下名为fruit的属性,而不是解析fruit变量存储的实际输入值,所以才会抛出AttributeError。

如果要通过动态变量的值作为键访问字典内容,需要使用方括号[]语法,将变量放在方括号内即可。你只需要把原代码中print行的fruits.fruit替换为fruits[fruit]即可正常运行。

修正后的完整代码如下:

import time

fruits={
    "apple":"Malus domestica",
    "banana":"Musa acuminata",
    "orange":"Citrus sinensis",
    "lychee":"Litchi chinensis",
}

fruit=input("Enter a fruit(either an apple, banana, orange, or lychee):")

if fruit in fruits:
    print("Your fruit's scientific name is "+fruits[fruit]+"\n")
else:
    print("Sorry, the fruit you entered was not in the database")

你也可以用字典的get方法简化代码,省去手动判断键是否存在的步骤:

# get方法第一个参数是键,第二个参数是键不存在时返回的默认值
sci_name = fruits.get(fruit, "Sorry, the fruit you entered was not in the database")
print(sci_name)

内容的提问来源于stack exchange,提问作者DataGhost

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 13:15:04