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
相关产品推荐
相关产品推荐

