Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

defaultdict and datetime

685 views
Skip to first unread message

Jason Friedman

unread,
Aug 18, 2018, 11:44:14 AM8/18/18
to
$ python3
Python 3.6.1 (default, Apr 8 2017, 09:56:20)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import collections, datetime
>>> x = collections.defaultdict(int)
>>> x['something']
0
>>> x = collections.defaultdict(datetime.datetime)
>>> x['something']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Required argument 'year' (pos 1) not found

I would like to have a dictionary where the default value is a
datetime.datetime object, preferably something small like January 1, year 1.

MRAB

unread,
Aug 18, 2018, 12:48:09 PM8/18/18
to
For the value you can use datetime.datetime.min.

The argument to defaultdict must be a function that takes no arguments.
You can use lambda for that:

x = collections.defaultdict(lambda: datetime.datetime.min)
0 new messages