Python中如何访问嵌套字典里espresso的cost值?
解决嵌套字典中访问espresso的cost值问题
你的menu是嵌套字典,顶层键是饮品名称("espresso"、"latte"、"cappuccino"),"cost"并不是顶层字典的直接键,而是每个饮品对应的子字典里的键,所以menu["cost"]会因找不到顶层键而失败。
正确访问方式
直接通过链式索引,先定位到"espresso"对应的子字典,再从中取出"cost"值:
espresso_cost = menu["espresso"]["cost"] print(espresso_cost) # 输出: 1.5
安全访问(避免键不存在报错)
如果担心"espresso"或"cost"键可能不存在,可以用字典的get()方法,避免抛出KeyError:
espresso_cost = menu.get("espresso", {}).get("cost") # 若espresso不存在,返回None;若存在但无cost键,也返回None
内容的提问来源于stack exchange,提问作者Helal_Python
相关产品推荐
相关产品推荐

