I'm trying to process data from a CSV file that checks if specific clinic codes are present in each line at index 2 and then update the corresponding dictionary. I previously had an if-elif chain to handle this, but as we are adding more clinics to our testing lab's clientele, this will quickly become an unsustainable practice.
I basically want a way to dynamically call and update the dictionary variable without knowing which one out of the list it will be. This is what I came up with, which gives KeyError: 'clinic'
in response to the line: if item['clinic'] == currentLine[2]:
, indicating that the item
iterator isn't functioning as a stand-in for the underlying dictionary.
#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.')
Old version (working, but becomes cumbersome as more clinics are added):
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.')