Convert month name to month number faster

alex23 wuwei23 at
Wed Jan 6 12:58:39 CET 2010

On Jan 6, 9:03 pm, wiso <gtu2... at> wrote:
> I'm optimizing the inner most loop of my script. I need to convert month
> name to month number. I'm using python 2.6 on linux x64.
> month_dict = {"Jan":1,"Feb":2,"Mar":3,"Apr":4, "May":5, "Jun":6,
>            "Jul":7,"Aug":8,"Sep":9,"Oct":10,"Nov":11,"Dec":12}
> def to_dict(name):
>   return month_dict[name]

Try replacing the to_dict function with:

   to_dict = month_dict.get

That removes one extra function call per lookup. On my computer, this
reduces the time for your test from 0.26 to 0.09.

More information about the Python-list mailing list