Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8369639
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T13:42:07+00:00 2026-06-09T13:42:07+00:00

I have a text file, and I want to load it into a dictionary

  • 0

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()
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-09T13:42:08+00:00Added an answer on June 9, 2026 at 1:42 pm

    Since your field names are all valid Python identifiers, why not read your data into namedtuples instead of dicts?

    data = """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  INJECTABLE""".split('; ')
    
    from collections import namedtuple
    
    # define class DrugData as a namedtuple, using the headers from data[0]
    DrugData = namedtuple("DrugData", data[0])
    
    # use a list comprehension to create a DrugData for each data line
    druglist = [DrugData(*line.split('\t')) for line in data[1:]]
    
    # access each tuple in druglist, using attribute access to individual fields
    for d in druglist:
        print "%s | %s | %s" % (d.ReferenceDrug, d.Form, d.Dosage)
    

    Prints:

    LIQUAEMIN | INJECTION | 20,000 UNITS/ML
    LIQUAEMIN | INJECTION | 40,000 UNITS/ML
    LIQUAEMIN | INJECTION | 5,000 UNITS/ML
    

    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 same drugname. 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 drugname points 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:

    from collections import defaultdict
    

    and change the declaration of meds_dict to:

    meds_dict = defaultdict(list)
    

    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:

    meds_dict[DrugName].append(meds)
    

    Now for any DrugName, you’ll get the list of matching Form/Dosage/etc. records.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have entries in a text file which I want to load into a
Say I have a text file that looks like this: date 1/1/2010 a,b,c a,b,d
I have a text file that I want to send over the network, this
I have a huge text file which I want to explode into an array.
I have a text file with hundreds of entries formatted like this, I need
I have a .sql file and I want to load it into MySQL database.
I have a text file that contains paragraphs of text. I want to load
I have been trying to load a text file into a combobox, and then
I have a text file that I want to edit by rewriting it to
I have a text file that I want to edit using Java. It has

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.