Working with files in python

So I have a insurance.csv file I made into a dictionary with the code below, it makes the dictionary great with no problems. Each entry in the dictionary looks like this:

{1: {‘age’: ‘19’, ‘sex’: ‘female’, ‘bmi’: ‘27.9’, ‘children’: ‘0’, ‘smoker’: ‘yes’, ‘region’: ‘southwest’, ‘charges’: ‘16884.924’}

insurance_dict = {}

with open('insurance.csv', newline = '') as insurance_file:
    insurance_data = csv.DictReader(insurance_file)
    count = 0
    for line in insurance_data:
        count += 1
        insurance_dict[count] = line

I want to check how smoking alters a persons insurance cost so I’m taking the results that have 0 children and then finding if they are a smoker. I’m using this code to simplify but here’s what I have.

for v in insurance_dict.values():
    if v['children'] == 0:
        if v['smoker'] == 'yes':
            print(v)

This code doesn’t throw an error but it doesn’t print. What am missing?
Thanks

I am not too sure but to me it seems strange that the values of the dictionary can have an integer value and str value at the same time. Your approach to solving this problem is too complex for me to fix lol. Sorry I couldnt help.

1 Like

I think it’s this line right here. The values you’re looking through are all strings, so the 0 has to be in quotes. Or you could convert it to an int.

2 Likes

So I tried this:

for v in insurance_dict.values():
    if int(v['children']) == 0:
        if v['smoker'] == 'yes':
            print(v)

converting the value to an int but it still won’t print(v)

I also tried this, with no luck:

for v in insurance_dict.values():
    if v['children'] == '0':
        if v['smoker'] == 'yes':
            print(v)

hm. I’m not so sure how to fix it then. If it helps, try using a debugger or printing certain variables to get an idea of what’s going on.

I figured it out, smoker isn’t yes or no anymore I changed it to 1 or 0. Changing the v[‘children’] to int(v[‘children’]) was helpful though I did miss that, thanks everyone!

1 Like