I have an CSV file that contains name of some series, her worth and her genre.
Example:
Descendant Without A Conscience,505.4,happy
Wolf Of The Solstice,30000,sad
Women Of Hope,-4000,neutral
I need to print a dictionary that gives the average worth of the series of the same genre:
{'happy': 192421.475, 'sad': 1659412.5, 'neutral': 30733.5'}
The only genres that are valid are happy, sad and neutral.
This is what I have tried:
d = {}
file_to_check = open('in_file.txt', 'r')
sum_for_happy = 0
sum_for_sad = 0
sum_for_neutral = 0
count_of_happy = 0
count_of_sad = 0
count_of_neutral = 0
for line in file_to_check:
lst = []
lst = line.rstrip().split(',')
if lst[2] == 'happy':
sum_for_happy += float(lst[1])
count_of_happy += 1
continue
if lst[2] == 'sad':
sum_for_sad += float(lst[1])
count_of_sad += 1
continue
if lst[2] == 'neutral':
sum_for_neutral += float(lst[1])
count_of_neutral += 1
continue
if sum_for_happy == 0 :
value_for_happy = 'NA'
else:
value_for_happy = sum_for_happy / count_of_happy
if sum_for_sad == 0 :
value_for_sad = 'NA'
else:
value_for_sad = sum_for_sad / count_of_sad
if sum_for_neutral == 0 :
value_for_neutral = 'NA'
else:
value_for_neutral = sum_for_neutral / count_of_neutral
d = {'happy':value_for_happy, 'sad':value_for_sad, 'neutral':value_for_neutral}
return d
But don't matter what values are in the CSV file the output is always the same:
{'happy': 'NA', 'sad': 'NA', 'neutral': 'NA'}
Like it does not enter the for loop at all and I can't understand why.