In: Computer Science
How can I get the days to print in order (Monday, Tuesday, Wednesday etc)
def summarize_by_weekday(expense_list):
"""
Requirement 3 to display the total amount of money spent on each
weekday, aggregated per day.
That is, display “Monday: $35”, “Tuesday: $54”, etc., where $35 is
the sum of dollar amounts for a
ll Mondays present in the data file, $54 is the sum of dollar
amounts for all Tuesdays present in the data file,
and so on.
:param expense_list:
:return: None
"""
weekday_spent_dict={}
for expense in expense_list:
if weekday_spent_dict.get(expense[0])==None:
weekday_spent_dict[expense[0]]=expense[1]
else:
weekday_spent_dict[expense[0]] += expense[1]
for day in sorted(weekday_spent_dict.keys()):
print('{0}: ${1:5.2f}'.format(day,weekday_spent_dict.get(day)))
output is:
Enter 1 display all of the expense records
2 to display all of the expense records for a particular
category
3 to display the total amount of money spent on each weekday,
aggregated per day
0 to quit.3
Friday: $94.90
Monday: $40.75
Saturday: $201.38
Sunday: $305.44
Thursday: $276.49
Tuesday: $14.85
Wednesday: $14.85
I want it to print:
Monday
Tuesday
Wednesday
etc..
def get_data(fname):
fileObj = open(fname)
lines = fileObj.readlines()
expense_list = []
for line in lines[1:]: # for lines starting at 2 (excluding 1
because it is the
line_items = line.strip().split(",") # strip removes the newline
character
expense_list.append([line_items[0], float(line_items[1]),
line_items[2]])
return expense_list
def summarize_by_weekday(expense_list): """ Requirement 3 to display the total amount of money spent on each weekday, aggregated per day. That is, display “Monday: $35”, “Tuesday: $54”, etc., where $35 is the sum of dollar amounts for all Mondays present in the data file, $54 is the sum of dollar amounts for all Tuesdays present in the data file, and so on. :param expense_list: :return: None """ weekday_spent_dict={} for expense in expense_list: if weekday_spent_dict.get(expense[0])==None: weekday_spent_dict[expense[0]]=expense[1] else: weekday_spent_dict[expense[0]] += expense[1] days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] for day in days: if day in weekday_spent_dict: print('{0}: ${1:5.2f}'.format(day, weekday_spent_dict.get(day)))
************************************************** You can define the ordering of days in a list, and then check the data for each day because monday tuesday etc do not have a ordering on basis of their english names. Thanks for your question. We try our best to help you with detailed answers, But in any case, if you need any modification or have a query/issue with respect to above answer, Please ask that in the comment section. We will surely try to address your query ASAP and resolve the issue.
Please consider providing a thumbs up to this question if it helps you. by Doing that, You will help other students, who are facing similar issue.