0

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.')
dissemin8or
  • 126
  • 6

1 Answers1

0

Since I seem to be the only one who cares about this problem, I guess I'll post my own solution. Context: clinic dicts have the naming convention 'ward'+'Metrics' and currentLine[2] contains the 'ward' part.

The answer is to use locals() or globals() as appropriate.

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

This allows the dict variable to be both called and modified without having to know which one out of the list it was to begin with. This is insecure, so don't use for unknown input data.

dissemin8or
  • 126
  • 6