I have a text file, and I want to load it into a dictionary in Python.
text looks like this, tab delimiated:
Form Dosage ReferenceDrug drugname activeingred
INJECTABLE; INJECTION 20,000 UNITS/ML LIQUAEMIN SODIUM HEPARIN SODIUM
INJECTABLE; INJECTION 40,000 UNITS/ML LIQUAEMIN SODIUM HEPARIN SODIUM
INJECTABLE; INJECTION 5,000 UNITS/ML LIQUAEMIN SODIUM HEPARIN SODIUM
And right now my code looks like this, but it does not work (list index out of range, and nothing pushed to the dictionary). I dont know where I’m going wrong, not a programmer. Thanks for any help.
import sys
def load_medications(filename):
meds_dict = {}
f = open(filename)
l = " "
# print f.read()
for line in f:
fields = l.split("\t")
ApplNo = fields[0]
ProductNo = fields[1]
Form = fields[2]
Dosage = fields[3]
ProductMktStatus = fields[4]
TECode = fields[5]
ReferenceDrug = fields[6]
DrugName = fields[7]
ActiveIngred = fields[8]
meds = {
"ApplNo": ApplNo,
"ProductNo": ProductNo,
"Form": Form,
"Dosage": Dosage,
"ProductMktStatus": ProductMktStatus,
"TECode": TECode,
"ReferenceDrug": ReferenceDrug,
"DrugName": DrugName,
"ActiveIngred": ActiveIngred
}
meds_dict[DrugName] = meds
f.close()
return meds_dict
def main():
x = load_medications("druglist.txt")
print x
if __name__ == "__main__":
main()
Since your field names are all valid Python identifiers, why not read your data into namedtuples instead of dicts?
Prints:
EDIT:
Looking back at your original question, it looks like you want to create a single dict of all of these entries, keyed by
drugname. Unfortunately, dict keys have to be unique, and in your example, all 3 entries have the samedrugname. You may have to combine 2 or more fields to compose a truly unique key for a dict that handles all of these values, such as a tuple of(drugname, Dosage).OR, change your design slightly so that each
drugnamepoints to a list of matching values. The simplest would be to use a defaultdict instead of a dict, so that new entries are automatically initialized with an empty list. In your code, you would add an import statement:and change the declaration of meds_dict to:
meaning that any new keys that haven’t been seen yet will be initialized using the function/class provided as the argument to defaultdict, in this case
list.Then to add new entries to meds_dict, instead of assigning with ‘=’, you would append to the list of all matching meds/dosages:
Now for any DrugName, you’ll get the list of matching Form/Dosage/etc. records.