defaultdict and datetime

MRAB python at mrabarnett.plus.com
Sat Aug 18 12:47:41 EDT 2018


On 2018-08-18 16:43, Jason Friedman wrote:
> $ 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.
> 
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)



More information about the Python-list mailing list