我创建了一本字典,但不断收到关键错误,我尝试了替代方案,但没有任何效果

问题描述 投票:0回答:1

下面是我编写的代码,下面是我得到的输出。我能够运行并打印 Transaction_Dict,但是当我尝试运行“Coffee = Transaction_Dict['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_Dict['Type']
  Amount = Transaction_Dict['Total']
  Total_Spent[Coffee] += Amount
  Total_Weight += Amount / CT_Dict[Coffee] 

KeyError                                  Traceback (most recent call last)
<ipython-input-20-3ec8797f18f1> in <cell line: 22>()
     21 
     22 for transaction in Transaction_Dict.values():
---> 23   Coffee = Transaction_Dict['Type']
     24   Amount = Transaction_Dict['Total']
     25   Total_Spent[Coffee] += Amount

KeyError: 'Type'

python dictionary key keyerror
1个回答
0
投票

您试图在循环内错误地访问 Transaction_Dict 字典中的“Type”和“Total”键。您应该从事务变量访问这些键,该变量代表循环中的每个事务。这是更正后的代码:

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']
    Amount = transaction['Total']
    Total_Spent[Coffee] += Amount
    Total_Weight += Amount / CT_Dict[Coffee]
© www.soinside.com 2019 - 2024. All rights reserved.