tags:

views:

48

answers:

1

I am trying to create a function that can convert a month number to an abbreviated month name or an abbreviated month name to a month number. I thought this might be a common question but I could not find it online.

I was thinking about the calendar module. I see that to convert from month number to abbreviated month name you can just do calendar.month_abbr[num]. I do not see a way to go the other direction though. Would creating a dictionary for converting the other direction be the best way to handle this? Or is there a better way to go from month name to month number and vice versa?

+1  A: 

Creating a reverse dictionary would be a reasonable way to do this, because it's pretty simple:

dict((v,k) for k,v in enumerate(calendar.month_abbr))

or in recent versions of Python (2.7+ I believe)

{(v,k) for k,v in enumerate(calendar.month_abbr)}
David Zaslavsky
this isnt working for me for some reason, >>> d = dict(v,k for k,v in calendar.month_abbr) File "<stdin>", line 1SyntaxError: Generator expression must be parenthesized if not sole argument
Mark_Masoul
Hmmm, I did this and it worked... d = dict((v,k) for k,v in enumerate(calendar.month_abbr))
Mark_Masoul
@Mark_Masoul: What version of Python? Looks pretty old.
S.Lott
@S.Lott python v2.6.4
Mark_Masoul
calendar.month_abbr isn't a dictionary, it's a `<calendar._localized_month instance at 0x0164C9E0>`. The original version of David's code produced syntax errors in 2.6 and 3.1 -- both need `()` around v,k and both need enumerate for calendar.month_abbr, which I fixed.
Wayne Werner
Fixed it. I should have read the documentation more carefully, I missed that `calendar.month_abbr` was an array instead of a dictionary.
David Zaslavsky
That's why I like IPython - documentation AND a testing environment ;) (no Python 3.x port in the near future though, which is a bummer)
Wayne Werner