Python 中字典的 KeyError

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

我有 Excel 工作表。在工作表 [6] 上,我正在搜索一些特定的字符串并获取该行的行号和列值。然后我在工作表 [0] 中搜索特定字符串并将相应的值写入工作表 [0] 的第 5 列。 例如,我在工作表[6]中搜索“UC Care”“PP Visit”获取列值并将 UC Care 列值写入工作表[0]

UCR***1

行第5列

下面是我的代码,我收到错误:

如果 coinds_dict[test_name] 不是无:KeyError: UCR***1

我的代码有什么问题?

import numpy as np
import openpyxl as xl

book = xl.load_workbook('Mapping.xlsx')
# Get the values of the first column in the  worksheet[6]
cgs_values = np.array([[cell.value for cell in row] for row in
                   book.worksheets[6].iter_rows(min_row=2, max_row=300, min_col=3, 
max_col=3)])

# Create a dictionary to store the row numbers for each test in the workbook[0]
test_rows = {'UCR***1': None, 'POV***1': None, 'SOV***1': None}


# Create a dictionary to store the percentage for each test
coins_dict = {'UC Care': None, 'PP Visit': None, 'SP Visit': None}

# Iterate through the test names
 for test_name in ['UC Care', 'PP Visit', 'SP Visit']:

 # Find the row in the worksheet[6] that contains the text
    row_number = np.where(cgs_values == test_name)[0][0] + 2

# Get the value of the cell in the sixth column of that row
coins = book.worksheets[6].cell(row=row_number, column=6).value

# If the value of the cell is not empty, then calculate the  percentage
if coins is not None:
    # If the value of the cell in the seventh column is "Coins", then calculate the coins percentage and store it in the dictionary
    if book.worksheets[6].cell(row=row_number, column=7).value == "Coins":
        coins = book.worksheets[6].cell(row=row_number, column=6).value
        m1 = 100 - int(coins)
        coins_dict[test_name] = str(m1) + "%" + " " + "Coinsurance"
    # If the value of the cell in the seventh column is "Cody", then calculate the  percentage and store it in the dictionary
    elif book.worksheets[6].cell(row=row_number, column=7).value == "Cody":
        coins = book.worksheets[6].cell(row=row_number, column=6).value
        m1 = 100 - int(coins)
        coins_dict[test_name] = str(m1) + "%" + " " + "after deductible"
   

# Find the row numbers for each test in the  workbook[0]
 for test_name, row_name in test_rows.items():
   for row in book.worksheets[0].iter_rows(min_row=1, max_row=book.worksheets[0].max_row, 
   min_col=1, max_col=1):
   if row[0].value == test_name:
        test_rows[test_name] = row[0].row
        break
   if coins_dict[test_name] is not None:
    book.worksheets[0].cell(row=test_rows[test_name], column=5, value=coins_dict[test_name])




  book.save('Mapping.xlsx')
  book.close()
python openpyxl
1个回答
0
投票

问题是

coinds_dict[test_name]
的值为
None
test_name
根本不是
coinds_dict
中的有效密钥之间存在差异。

您可以显式处理异常,但我认为使用以下内容更符合习惯:

if test_name not in coinds_dict:
   ...

要包括密钥为

None
的情况,您可以这样做:

if test_name not in coinds_dict and coinds_dict[test_name] is not None:
   ...
© www.soinside.com 2019 - 2024. All rights reserved.