using datetime containers

Peter Otten __peter__ at web.de
Sat Nov 8 11:56:00 EST 2008


indika wrote:

> Hi,
> I'm a newbie to python but have some experience in programming.
> I came across this requirement of using datetime.date objects
> associated with some another object.
> eg. a dictionary containing datetime.date => string
>>>
> {
> datetime.date(2001, 12, 3): 'c',
> datetime.date(2001, 12, 1): 'a',
> datetime.date(2001, 12, 2): 'b'
> }
> 
> However, the sorting of the dict is not user configurable.  The
> desired behavior would be to provide a datetime.date comparison
> function to do the sorting(eg. STL map). This may seem a trivial
> question but I couldn't figure out a way.
> 
> Or else, I would have expected the datatime.date object has a
> writeable data member, so that iterating a calender with
> itermonthdates would allow me to access that data member.
> 
> I would really appreciate if you would give me some pointers into
> this.

Do the simplest thing that works for you. If you need your dictionary
ordered for output only, just sort it:

>>> dmap = {
... datetime.date(2001, 12, 3): 'c',
... datetime.date(2001, 12, 1): 'a',
... datetime.date(2001, 12, 2): 'b'
... }
>>> for date, value in sorted(dmap.items()):
...     print date, "-->", value
...
2001-12-01 --> a
2001-12-02 --> b
2001-12-03 --> c

Peter



More information about the Python-list mailing list