[Python] Why is my code updating all nested dictionaries instead of only the specified nested...

Discussão em 'Python' iniciado por Stack, Junho 27, 2025.

  1. Stack

    Stack Membro Participativo

    The following code creates a dictionary with the structure:

    {region1: {female: count, male: count}, region2: {female: count, male: count}, (...) }


    I would expect my code to update only the current region's nested dictionary on each iteration of the for loop... yet instead it's updating every region's nested dictionary, such that the results have each region with the same counts of both parameters in their respective nested dictionaries. Why is that?

    def counts_per_region(dictionary, counting):
    results = dict.fromkeys(regions, {})
    for item in dictionary:
    region = dictionary.get(item).get('region')
    param_value = dictionary.get(item).get(counting)
    count = results.get(region).get(param_value, 0)
    updated_count = count + 1
    results[region][param_value] = updated_count
    print(results)
    #return results


    Calling the function with:

    counts_per_region(med_ins_cost_dict, 'sex')


    returns the following (showing first row only):

    {'southwest': {'female': 1}, 'southeast': {'female': 1}, 'northwest': {'female': 1}, 'northeast': {'female': 1}}


    Whereas it should return:

    {'southwest': {'female': 1}, 'southeast': {}, 'northwest': {}, 'northeast': {}}


    Here are the two last rows in med_ins_cost_dict:

    (1333, {'age': '50', 'sex': 'male', 'bmi': '30.97', 'children': '3', 'smoker': 'no', 'region': 'northwest', 'charges': '10600.5483'})
    (1334, {'age': '18', 'sex': 'female', 'bmi': '31.92', 'children': '0', 'smoker': 'no', 'region': 'northeast', 'charges': '2205.9808'})

    Continue reading...

Compartilhe esta Página