On Thu, 7 Aug 2008, bob gailer wrote:

Christopher Spears wrote:
Hey,

I'm working on a problem out of Core Python Programming (2nd Edition). Basically, I'm creating a class that formats dates. Here is what I have so far:


Consider reformatting the month_dict so each name and abbreviation is a key. Then you can just look up the potential key rather than looping thru all the keys. That is what dictionaries are for!:

        month_dict = {"jan" : 1,
                      "january" : 1,
                      "feb" : 2,
                    "february" :2, etc ...}
      ...
        except ValueError:
                 if month.lower() in month_dict:
                    month = month_dict[month.lower()]
                 else:
                      month = ""

The dict function is also handy here:

        month_dict = dict(
                     jan = 1,
                       january = 1,
                       feb = 2,
                     february = 2, etc ...)

Dear Christopher,

Instead of multiplying the keys for each possible version of the written month, I would rather have:

month_dict = {"jan":1,
              "feb":2, ...}

and have:
written_month = written_month[:3].lower()
if written_month in month_dict:
    # do something

Regards,
Benoit.
_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to