Thought the project was medium difficulty for a newbie which is perfect. I only just realised I could’ve used a Class implementation which I’ll have a go at next.
My code is pretty basic without much commentary so any feedback welcome on the logic.
import csv
with open("insurance.csv") as insurance_csv:
medi_dict = {}
csvreader = csv.reader(insurance_csv, delimiter=',')
fieldnames = next(csvreader)
age = []
sex = []
bmi = []
children = []
smoker = []
region = []
charges = []
for i in csvreader:
age.append(i[0])
sex.append(i[1])
bmi.append(i[2])
children.append(i[3])
smoker.append(i[4])
region.append(i[5])
charges.append(i[6])
def average_age(list):
total = 0
for i in list:
total += int(i)
average = total / len(list)
return average
av_age = average_age(age)
print("Average Age for data set is: " + str(av_age))
def most_common_region(list):
common_region = {}
counter = 0
commreg = ''
for r in list:
common_region[r] = 0
for r in list:
if r in common_region:
common_region[r] += 1
for key, value in common_region.items():
if value >= counter:
counter = value
print("Most common region is: ")
print(common_region.keys()[common_region.values().index(counter)], counter)
comm_region = most_common_region(region)
def create_dictionary(age, sex, bmi, children, smoker, region, charges):
medical = {}
for i in range(len(age)):
medical[i] = {"Age": age[i],
"Sex": sex[i],
"BMI": bmi[i],
"Children": children[i],
"Smoker": smoker[i],
"Region": region[i],
"Charges": charges[i]}
return medical
med_dict = create_dictionary(age, sex, bmi, children, smoker, region, charges)
def smoke_non_smoke(dictionary):
total = 0.0
count = 0
for i in dictionary:
if dictionary[i]["Smoker"] == "yes":
count += 1
total = float(dictionary[i]["Charges"]) + total
limited_total = round(total, 2)
av_smoke_charge = limited_total / count
ntotal = 0.0
ncount = 0
for i in dictionary:
if dictionary[i]["Smoker"] == "no":
ncount += 1
ntotal = float(dictionary[i]["Charges"]) + ntotal
limited_ntotal = round(ntotal, 2)
av_nsmoke_charge = limited_ntotal / ncount
print("The Average charge for a smoker vs non-smoker is: ")
print(round(av_smoke_charge,2), round(av_nsmoke_charge,2))
diff_smoke = smoke_non_smoke(med_dict)
def av_parent_one_child(dictionary):
count = 0
total_a = 0
for i in dictionary:
if dictionary[i]["Children"] == "1":
total_a = int(dictionary[i]["Age"]) + total_a
count += 1
average_age_one = int(total_a) / int(count)
print("The average age for a parent with one child is: " + str(average_age_one))
one_child_rent = av_parent_one_child(med_dict)
def male_v_female(dictionary):
male = 0
female = 0
for i in dictionary:
if dictionary[i]["Sex"] == "male":
male += 1
else:
female += 1
print(male, female)
males_females = male_v_female(med_dict)