如何使用字典列表根据文本文件中的数据更新正确字典中的值?

How do I use a list of dictionaries to update values in the correct dictionary based on data in text file?

我正在尝试处理来自 CSV 文件的数据,该文件检查索引 2 处的每一行中是否存在特定诊所代码,然后更新相应的字典。我以前有一个 if-elif 链来处理这个问题,但随着我们为测试实验室的客户增加更多诊所,这将很快成为一种不可持续的做法。

我基本上想要一种动态调用和更新字典变量的方法,而无需知道它将是列表中的哪一个。这是我想出的,它给出 KeyError: 'clinic' 响应行:if item['clinic'] == currentLine[2]:,表明 item 迭代器没有作为基础字典的替代品。

#please assume all dicts are properly set up with keys and default values 
clinic1, clinic2, clinic3, clinic4 = {}, {}, {}, {}
clinicList = [clinic1, clinic2, clinic3, clinic4]
populateDictFunction(clinic1, clinic2, clinic3, clinic4)

for line in infile: currentLine = line.split()          
    found = False
#problem area here--v
    for item in clinicList:
        if item['clinic'] == currentLine[2]:
            specimenType, item = specimenAdderFunction(item, currentLine[3])
            found = True
    if found == False:
        print(currentLine[2], 'is not a supported clinic.')

旧版本(工作,但随着更多诊所的增加变得很麻烦):

if currentLine[2] == 'clinic1':
    specimenType, clinic1= specimenAdder(clinic1, currentLine[3])
elif prevLine[2] == 'clinic2':
    specimenType, clinic2= specimenAdder(clinic2, currentLine[3])
else:
    print(currentLine[2], 'is not recognized.')

因为似乎只有我一个人关心这个问题,所以我想我会 post 我自己的解决方案。上下文:诊所字典具有命名约定 'ward'+'Metrics' 并且 currentLine[2] 包含 'ward' 部分。

答案是酌情使用locals()globals()

for item in clinicList:
    if item['Clinic'] == currentLine[2]:
        specimenType, locals()[currentLine[2]+'Metrics'] = specimenAdderFunction(locals()[currentLine[2]+'Metrics'], currentLine[3])

这允许调用和修改 dict 变量,而不必知道它是从列表中的哪一个开始的。这是不安全的,所以不要用于未知的输入数据。