monthdays = {'Jan':31, 'Feb':28, 'Mar':31,
'Apr':30, 'May':31, 'Jun':30,
'Jul':31, 'Aug':31, 'Sep':30,
'Oct':31, 'Nov':30, 'Dec':31}
months = monthdays.items()
months.sort(lambda f, s: cmp(f[1], s[1]))
for month, days in months:
print("There are ",days," days in a ", month)
Error
Error:
Exception has occurred: AttributeError
'dict_items' object has no attribute 'sort'
File "/home/Desktop/dictionaries.py", line 7, in <module>
months.sort(lambda f, s: cmp(f[1], s[1]))
Objective get a list of tuple pairs using the items method
Use
months = list(monthdays.items())
I don't know what you want to do, but months are always sorted
monthdays = {'Jan':31, 'Feb':28, 'Mar':31,
'Apr':30, 'May':31, 'Jun':30,
'Jul':31, 'Aug':31, 'Sep':30,
'Oct':31, 'Nov':30, 'Dec':31}
for month in monthdays:
print(f"There are {monthdays[month]} days in {month}")
Output:
There are 31 days in Jan
There are 28 days in Feb
There are 31 days in Mar
There are 30 days in Apr
There are 31 days in May
There are 30 days in Jun
There are 31 days in Jul
There are 31 days in Aug
There are 30 days in Sep
There are 31 days in Oct
There are 30 days in Nov
There are 31 days in Dec
(Jul-29-2022, 09:10 PM)Gribouillis Wrote: [ -> ]Use
months = list(monthdays.items())
It's saying
Error:
sort() takes no positional arguments
(Jul-29-2022, 09:12 PM)Calli Wrote: [ -> ]It's saying Error:sort() takes no positional arguments
Use
months = sorted(monthdays.items(), key=lambda p: p[1])
(Jul-29-2022, 09:15 PM)Gribouillis Wrote: [ -> ] (Jul-29-2022, 09:12 PM)Calli Wrote: [ -> ]It's saying Error:sort() takes no positional arguments
Use
months = sorted(monthdays.items(), key=lambda p: p[1])
Thank you so much works like charm now
(Jul-29-2022, 09:17 PM)Calli Wrote: [ -> ]Thank you so much works like charm now
A slightly more educated version:
from operator import itemgetter
months = sorted(monthdays.items(), key=itemgetter(1))