'Create a dictionary whose keys are month names and values are no. of days in the corresponding month. #program stack

please correct the code. Create a dictionary whose keys are month names and values are no. of days in the corresponding month. WAP with separate user defined functions to implement the following operations. (i)push only those names on the stack whose no. of days are 31. (ii) pop and display the content of the stack.

plzz correct the code code: https://docs.google.com/document/d/1fj3eaa2zXIkwhE6W4apLjmva44hxi51C/edit



Solution 1:[1]

This is probably what you wanted

Edit: Edited the code to meet the new requirements.

(I don't understand what do you mean by 'stack' but you can continue from here)

def create_month_day_dict(year, long_only=False):
    months_names = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October',
                    'November', 'December']
    days_in_month = [31, 28 + (year % 4 == 0), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

    return dict((k, v) for k, v in zip(months_names, days_in_month) if not long_only or v == 31)


print(create_month_day_dict(2022, long_only=True))
print(create_month_day_dict(2024))

output:

{'January': 31, 'March': 31, 'May': 31, 'July': 31, 'August': 31, 'October': 31, 'December': 31}

{'January': 31, 'February': 29, 'March': 31, 'April': 30, 'May': 31, 'June': 30, 'July': 31, 'August': 31, 'September': 30, 'October': 31, 'November': 30, 'December': 31}

Note: also considered the relevant year

Solution 2:[2]

You need to consider the year when building a dictionary to help with this problem. The calendar module is ideal for this:

from calendar import monthrange, month_abbr

def make_dictionary(year):
    d = {'year': year}
    for i in range(1, 13):
        d[month_abbr[i]] = monthrange(year, i)[1]
    return d
    
print(make_dictionary(2024))

Output:

{'year': 2024, 'Jan': 31, 'Feb': 29, 'Mar': 31, 'Apr': 30, 'May': 31, 'Jun': 30, 'Jul': 31, 'Aug': 31, 'Sep': 30, 'Oct': 31, 'Nov': 30, 'Dec': 31}

If you want the full (rather than abbreviated) month name then import month_name and use that

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Albert Winestein