Python Forum
Doesn't look like a dictionary
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Doesn't look like a dictionary
#11
Sounds like it only outputs one value or the other depending on usage.

historic_levels, scan_levels = [], []
for datum in data:
    if datum['Historic Glucose (mg/dL)']:
        historic_levels.append(int(datum['Historic Glucose (mg/dL)']))
    else:
        scan_levels.append(int(datum['Scan Glucose (mg/dL)']))
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#12
Here is how I would do it (probably :-), if I don't go OOP)
Using namedtuple from collections module to make the code more readable

from collections import namedtuple, OrderedDict
import csv

# define namedtuple Patient. It will represent individual patient data (i.e. single row from csv)
Patient = namedtuple('Patient', ['id', 'hist_glucose', 'scan_glucose'])

# read the csv file
with open('summary.txt') as f:
    reader = csv.DictReader(f, delimiter=',')
    # this will be OrderedDict to hold all data
    patients = OrderedDict()
    
    # iterate over file
    for row in reader:
        patient_id = int(row['ID']) # convert id to int

        # try to convert Historic Glucose
        try:
           hist_glucose = int(row['Historic Glucose (mg/dL)'])
        except ValueError:
           hist_glucose = 0 # default value of 0
        
        # try to convert Scan Glucose
        try:
           scan_glucose = int(row['Scan Glucose (mg/dL)'])
        except ValueError:
           scan_glucose = 0
        
        # add current patient to patients
        patients[patient_id] = Patient(patient_id, hist_glucose, scan_glucose)


# iterate over patients and print each patient
for patient in patients.values():
    print(patient)

# calculate number of patients
num_patients = len(patients)
print('Number of patients: {}'.format(num_patients))

# calculate average historic glucose
ave_historic = sum(patient.hist_glucose for patient in patients.values())/num_patients
print('Historic Glucose average : {:.3f}'.format(ave_historic))

# calculate average scan glucose
ave_scan = sum(patient.scan_glucose for patient in patients.values())/num_patients
print('Scan Glucose average : {:.3f}'.format(ave_scan))

# access individual patient data
print('Patient {id}, Historic Glucose: {hist_glucose} (mg/dL)'.format(**patients[132]._asdict()))
assuming this is the sample input file (note there is bad record, id=135)
Output:
ID,Time,Record Type,Historic Glucose (mg/dL),Scan Glucose (mg/dL),Non-numeric Rapid-Acting Insulin,Rapid-Acting Insulin (units),Non-numeric Food,Carbohydrates (grams),Non-numeric Long-Acting Insulin,Long-Acting Insulin (units),Notes,Strip Glucose (mg/dL),Ketone (mmol/L),N/A,Previous Time,Updated Time 132,2018/07/28 01:41,0,141,,,,,,,,,,,,,,, 133,2018/07/28 01:56,0,133,,,,,,,,,,,,,,, 134,2018/07/28 02:11,0,126,,,,,,,,,,,,,,, 135,2018/07/28 02:27,1,,123,,,,,,,,,,,,,, 137,2018/07/28 02:27,0,126,,,,,,,,,,,,,,, 138,2018/07/28 02:42,0,119,,,,,,,,,,,,,,, 139,2018/07/28 02:57,0,96,,,,,,,,,,,,,,,
the output from running the script is
Output:
Patient(id=132, hist_glucose=141, scan_glucose=0) Patient(id=133, hist_glucose=133, scan_glucose=0) Patient(id=134, hist_glucose=126, scan_glucose=0) Patient(id=135, hist_glucose=0, scan_glucose=123) Patient(id=137, hist_glucose=126, scan_glucose=0) Patient(id=138, hist_glucose=119, scan_glucose=0) Patient(id=139, hist_glucose=96, scan_glucose=0) Number of patients: 7 Historic Glucose average : 105.857 Scan Glucose average : 17.571 Patient 132, Historic Glucose: 141 (mg/dL)
of course more improvements are possible (there is a lot of room for improvements or doing things differently), but for start this also works
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#13
Gave it a try and got the error:

File "C:/Users/gary/PycharmProjects/sqlite/testcsv.py", line 15, in <module>
patient_id = int(row['ID']) # convert id to int
KeyError: 'ID'

I changed the delimiter from ',' to '\t' and it worked.

Thank you

One more quick fix.

I need to add the patient.hist_glucose and patient.scan_glucose together then get the average.

I figured out the total sum. PHP programming does come in handy once in a while.

Trying to learn python I have a couple of questions.
1. Can you explain what {:.3f} does? I assume the f is the file
2. try:
scan_glucose = int(row['Scan Glucose (mg/dL)'])
except ValueError:
scan_glucose = 0

Does that set scan_glucose to 0 or just bye pass it if scan_glucose is null?

Thank you for this great learning lesson.
Gary
Reply
#14
{:.3f} means to print the number in the format call as a floating point number (decimal) with three digits on the right of the decimal. You can see the full format method syntax here.

And yes, the try/except block sets it to zero, but it does that for any value that can't be converted to an integer.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#15
ichabood answered to your questions about string formatting and try/except.

(Dec-12-2018, 11:14 PM)gehrenfeld Wrote: I changed the delimiter from ',' to '\t' and it worked.

Now I am really confused. Till now you indicated your data to be comma-separated. Also all the code snippets using separator=',' worked (e.g. here and here). Now it turns your data are tab-separated. What's the actual format?

(Dec-12-2018, 11:14 PM)gehrenfeld Wrote: I need to add the patient.hist_glucose and patient.scan_glucose together then get the average.

I would suggest you try to do it yourself and come with code that we can discuss. Post your full code in python tags. I think this will be better for you learning the language. Also given the issue above (i.e. ',' or '\t' separator it would be nice if you share sample file so we all know what we work with).
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#16
I would like to thank everyone for their help.
I apologize for any confusion I caused. Sometimes when you have multiple people help and you try their suggestion things change and I forget to put them back to normal.
Gary
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Line of code to show dictionary doesn't work MaartenRo 2 2,440 Jul-28-2020, 03:58 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020