When for looping through dictionary, my code is returning individual characters instead of considering the entire string in a value

HI everyone, I am working on the portfolio project “U.S Medical Insurance Costs”


and I am trying to make a look that will go through specific keys and count the iterations of responses. I have imported the CSV file and turned it into a dictionary where each clients key is an integer and then the response is a dictionary of their data. When i run my for loop I get a count of each character that shows up in the value for example with smoker, which can give yes or no i get:

{‘y’: 274, ‘e’: 274, ‘s’: 274, ‘n’: 1064, ‘o’: 1064}

I am adding my code so far below

import csv

# creating an internal data set from CSV file for data analysis

insurance_costs = []
with open('insurance.csv', newline='') as csv_info:
    insurance_info = csv.DictReader(csv_info)
    for row in insurance_info:

# Changing from a list to a dictionary

insurance_dict = {}
for i, d in enumerate(insurance_costs):
    insurance_dict[i] = d


# Function for determining the % composition of variables:

def proportion_of_population(dictionary, key_var):
    rate_dictionary = {}
    for i in dictionary:
        for a in dictionary[i][key_var]:
            if a in rate_dictionary.keys():
                rate_dictionary[a] += 1
                rate_dictionary[a] = 1
    return rate_dictionary

print(proportion_of_population(insurance_dict, 'smoker'))

If you iterate through a string it returns each character in turn, for example-

for letter in 'hello': print(letter)

I’m guessing at some point the data is not the form you expect and you get this out instead. See if you can hunt down where it happens (something like print can help if you’re unsure).


Thanks! that makes perfect sense I think I am struggling with how to iterate through a dictionary and get the values extracted when the dictionary is within another dictionary. as I see it my issue is on the line with
for a in dictionary[i][key_var]:

I am iterating through the strings when what I want is to pull out possible value options and count them

Dictionaries have three similar methods that might be helpful here, .keys() provides the keys, .values() provides the values and .items() provides key, value pairs. For an example-

dct = { 'red': 3, 'green': 1, 'blue': 5, } for key in dct.keys(): print(f'key is {key}') for value in dct.values(): print(f'value is {value}') for key, value in dct.items(): print(f'key is {key}, value is {value}')
1 Like