[Python] How to access a value within a nested dictionary?

Discussão em 'Python' iniciado por Stack, Março 16, 2025.

  1. Stack

    Stack Membro Participativo

    My aim is to find the average insurance charges for both males and females respectively. I created a dictionary that I thought would make it easier for me to access the patients data and do the analysis which mainly consists of finding averages and Min & Max values based on specific patient attributes. See a snippet of my dictionary below:

    {0: {'ID': 0, 'Age': 19, 'Sex': 'female', 'BMI': '27.9', 'Children': '0', 'Smoker Status': 'yes', 'Region': 'southwest', 'Charges': '16884.924'}, 1: {'ID': 1, 'Age': 18, 'Sex': 'male', 'BMI': '33.77', 'Children': '1', 'Smoker Status': 'no', 'Region': 'southeast', 'Charges': '1725.5523'}}


    I have been stuck trying to get the charges for only the male patients and the charges for only the female patients into a list or dictionary so that I can add them together, as I already know how many male and female patients there are in the dataset. Here are two examples of what I tried and their outputs:

    Example 1:

    male_charges = []
    def m_charges(patients):
    gen = 'male'
    for patient in patients:
    for gender in patients[patient]['Sex']:
    if gen == gender:
    male_charges.append(patients[patient]['Sex'])
    return male_charges

    male_charges = m_charges(patients)
    print(male_charges)


    Outout: []

    Example 2:

    total_male_charges = 0
    male = 'male'

    for key, value in patients.items():
    for value in patients:
    if value == male:
    total_male_charges += patients['charges']
    print(total_male_charges)


    Output: 0

    Continue reading...

Compartilhe esta Página