Stuck Iterating through a Dict

Hi again!

I’m sorry to bother again, but I’m super stuck on this one.

I am looking at US Medical Insurance and would like to analyse the cost of the insurance but with a few conditions attached. For example I would like to select only men, non-smokers and living in the same region.
But I can’t manage to iterate through the dictionary to create these conditions and get the cost of the people who meet these specific conditions…

I leave the code below. I paste almost every line of the code, but the problem is the function inside the Class.

Thanks in advance!


ages = load_list_data(ages, "C:/Users/rodri.DESKTOP-RAT8004/Desktop/insurance.csv", "age")
sexes = load_list_data(sexes, "C:/Users/rodri.DESKTOP-RAT8004/Desktop/insurance.csv", "sex")
bmi = load_list_data(bmi, "C:/Users/rodri.DESKTOP-RAT8004/Desktop/insurance.csv", "bmi")
num_of_children = load_list_data(num_of_children, "C:/Users/rodri.DESKTOP-RAT8004/Desktop/insurance.csv", "children")
smoker_status = load_list_data(smoker_status, "C:/Users/rodri.DESKTOP-RAT8004/Desktop/insurance.csv", "smoker")
regions = load_list_data(regions, "C:/Users/rodri.DESKTOP-RAT8004/Desktop/insurance.csv", "region")
insurance_cost = load_list_data(insurance_cost, "C:/Users/rodri.DESKTOP-RAT8004/Desktop/insurance.csv", "charges")

def create_dictionary(ages, sexes, bmi, num_of_children, smoker_status, regions, insurance_cost):
    patients = dict()
    num_patients = len(ages)
    for i in range(num_patients):
        patients[i] ={"Age" : ages[i],
                     "Sex" : sexes[i],
                      "BMI" : bmi[i],
                      "Number of children" : num_of_children[i],
                      "Smoker" : smoker_status[i],
                      "Region" : regions[i],
                      "Insurance charge" : insurance_cost_int[i]                            
            
        }
    return patients
patients = create_dictionary(ages, sexes, bmi, num_of_children, smoker_status, regions, insurance_cost)


class PatientsInfo:
    # antes de definir cualquier función tenemos que rellenar la clase con las listas que vamos a utiliar y definir la función
    # __init__ con el argumento self asociado a cada lista
    def __init__(self, patients_ages, patients_sexes, patients_bmi, patients_num_of_children, 
                 patients_smoker_status, patients_regions, patients_insurance_cost, patients_patients):
        self.patients_ages = patients_ages
        self.patients_sexes = patients_sexes
        self.patients_bmi = patients_bmi
        self.patients_num_of_children = patients_num_of_children
        self.patients_smoker_status = patients_smoker_status
        self.patients_regions = patients_regions
        self.patients_insurance_cost = patients_insurance_cost
        self.patients_patients = patients_patients

    def analyze_cost_by_sex(self):
        total_male_cost = 0
        total_female_cost = 0
        for sex in self.patients_patients.values():
            gender = self.patients_patients["Sex"]["male"]
            if sex == gender:
                total_male_cost += float(self.patients_patients["charges"])
            else:
                total_female_cost += float(self.patients_patients["charges"])
                
        print("Average male cost: " + str(total_male_cost/len(total_male_cost))
        print("Average female cost: " + str(total_female_cost/len(total_female_cost))
    

Really thanks to anyone solving this!

I’m not totally sure of the structure of patients_patients, but I’m assuming it’s a dictionary of dictionaries that is using the patients themselves as keys.

For the analyze_cost_by_sex function, I think the following will work:

def analyze_cost_by_sex(self):
    total_male_cost = 0
    total_female_cost = 0
    male_count = 0
    female_count = 0

    for patient_values in self.patients_patients.values():
        if patient_values["sex"] == "male":
            total_male_cost += float(patient_values["charges"])
            male_count += 1
        else:
            total_female_cost += float(patient_values["charges"])
            female_count += 1

    print("Average male cost: " + str(total_male_cost/male_count))
    print("Average female cost: " + str(total_female_cost/female_count))

If I’m wrong, I would like some clarification on what patients_patients is.

1 Like

Hi, first thanks for taking your time answering me!

After using your code into my project it shows me this error:

This is the code is used for creating my dict (I don’t really know if it’s a dict of dictionaries, but I think it isn’t)

def create_dictionary(ages, sexes, bmi, num_of_children, smoker_status, regions, insurance_cost):
    patients = dict()
    num_patients = len(ages)
    for i in range(num_patients):
        patients[i] ={"Age" : ages[i],
                     "Sex" : sexes[i],
                      "BMI" : bmi[i],
                      "Number of children" : num_of_children[i],
                      "Smoker" : smoker_status[i],
                      "Region" : regions[i],
                      "Insurance charge" : insurance_cost_int[i]                            
            
        }
    return patients
patients = create_dictionary(ages, sexes, bmi, num_of_children, smoker_status, regions, insurance_cost)

I don’t know if it’s enough info or not.

Thanks again for your time! :slight_smile:

And this is how it looks when I print the dict patients: (couldn’t upload 2 files as I’m new)

Patients is a dict made out of 7 different lists that we’re filled with a .csv file, they have their own name and I when I made the function to create the dictionary I paired each list with a string with the name that defines it, just as it show in the code above.
Thanks again, I hope it’s enough info!

Looks like the error is a typo on my part, as it’s often the case for KeyError. In the analyze_cost_by_sex function, change the following line:

if patient_values["sex"] == "male":

to

if patient_values["Sex"] == "male":

Note the capitalization of S. The key has to be typed exactly the way it is spelled in the dictionary, lower case and upper case, in order to access the value.

Also, in the analyze_cost_by_sex function, replace every occurrence of

patient_values["charges"]

to

patient_values["Insurance charge"]

Again, the key index must be typed exactly how it’s spelled in the dictionary.

3 Likes

Yes, finally!

I managed to wirte that function and others thanks to those tips and code you gave me, I really appreciate the help!

Thanks <3