Write a function to do the following operations on the dictionary which holds month names as keys and number of days in the month as values
A)ask the user to enter a month name and display the corresponding number of days of that month
B)print all keys in the alphabetical order
C)Print all months that have 31 days
Answers
Months and Days - Python Dictionary
A Python Dictionary is a data structure that holds pairs of values. They are known as key and value pairs.
Each key is assigned a value. So, month names can be keys, and the number of days in each month can be values.
The syntax is pretty standard. A dictionary is within curly braces and has key: value pairs.
After that, we just have to define the functions and test them.
For the month names in alphebetical order, we get the keys with the .keys() function, convert it into a list and then we use the sort() function.
MonthsDictionary.py
# The months dictionary
months = {
"January": 31,
"February": 28,
"March": 31,
"April": 30,
"May": 31,
"June": 30,
"July": 31,
"August": 31,
"September": 30,
"October": 31,
"November": 30,
"December": 31
}
# Display the number of days in a month
def display_days(month_name):
return months[month_name]
# Print the month names in alphabetical order
def sort():
month_names = list(months.keys())
month_names.sort()
for i in month_names:
print(i)
# Print the months with 31 days
def print_months_with_31_days():
for month in months:
if months[month] == 31:
print(month)
# Test function
def main():
month = input("Enter month name: ")
print(f"Number of days in {month}: {display_days(month)}")
print("\n\nMonths in alphabetical order:")
sort()
print("\n\nMonths with 31 days:")
print_months_with_31_days()
if __name__ == "__main__":
main()
Answer:
year={"Jan":31,"Feb":28,"Mar":31,"Apr":30,"May":31,"Jun":30,"Jul":31,"Aug":31,"Sept":30,"Oct":31,"Nov":30,"Dec":31}
name=input("Enter the month name in short form:")
if name.capitalize() in year:
print("(a).No. of days in the month of",name,"is:",year[name.capitalize()],"days")
else:
print("Invalid month name")
print()
print("(b).Months sorted in alphabetical order are:\n",sorted(year))
print()
months=[]
for i in year:
if year[i]==31:
months.append(i)
print("(c).Months having 31 days are:\n",months)
print()
lst1=[]
lst2=[]
count=30
for i in year:
if year[i]<=count:
lst1.append((i,year[i]))
else:
lst2.append((i,year[i]))
print("(d).(key-value) pairs sorted by the number of days in each months are:\n",lst1+lst2)
Explanation: