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

Python字典KeyError问题求助:遍历Transaction_Dict时获取键值失败

解决字典遍历中的KeyError问题

你的问题出在循环遍历的逻辑上:

  • 你用for transaction in Transaction_Dict.values()遍历的是外层字典里的每个内层字典(比如{'Type': 'Classic', 'Total': 37.33})
  • 但你在循环里错误地尝试从外层字典Transaction_Dict中取'Type'和'Total'键,而外层字典的键是'T1'到'T10',根本没有'Type'这个键,所以触发KeyError。

修正后的代码如下:

CoffeeType = ['Classic','Breakfast Blend','Rev It Up']

Transaction_Dict = {
    'T1': {'Type': 'Classic', 'Total': 37.33},
    'T2': {'Type': 'Rev It Up', 'Total': 45.82},
    'T3': {'Type': 'Breakfast Blend', 'Total': 32.32},
    'T4': {'Type': 'Classic', 'Total': 47.75},
    'T5': {'Type': 'Classic', 'Total': 28.18},
    'T6': {'Type': 'Breakfast Blend', 'Total': 46.94},
    'T7': {'Type': 'Rev It Up', 'Total': 33.89},
    'T8': {'Type': 'Breakfast Blend', 'Total': 26.91},
    'T9': {'Type': 'Breakfast Blend', 'Total': 22.03},
    'T10': {'Type': 'Classic', 'Total': 33.35}}


CT_Dict = {'Classic': 3.50, 'Breakfast Blend': 4.00, 'Rev It Up': 5.00}
Total_Spent = {Type: 0 for Type in CoffeeType}
Total_Weight = 0

for transaction in Transaction_Dict.values():
  Coffee = transaction['Type']  # 从当前遍历的内层字典取Type
  Amount = transaction['Total']  # 从当前遍历的内层字典取Total
  Total_Spent[Coffee] += Amount
  Total_Weight += Amount / CT_Dict[Coffee] 

核心修正点:

  • 将Transaction_Dict['Type']改为transaction['Type'],Transaction_Dict['Total']改为transaction['Total'],直接从循环变量(每个交易的内层字典)中获取对应的值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 17:14:58