Ian Kelly wrote:

> One thing I will note as a disadvantage of defaultdict is that
> sometimes you only want the default value behavior while you're
> initially building the dict, and then you just want a normal dict with
> KeyErrors from then on.  defaultdict doesn't do that; once
> constructed, it will always be a defaultdict.  

This is one of the statements that I won't believe without trying myself. 
As I'm posting you can probably guess my findings:

>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> d[0]
0
>>> d.default_factory = str
>>> d[1]
''
>>> d.default_factory = None
>>> d[2]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 2
>>> d
defaultdict(None, {0: 0, 1: ''})

So you can change a defaultdict's default_factory any time you like, and if 
you set it to None there will be no default. It will still "be" a 
defaultdict, but it will act like a normal dict.

> You can copy the data
> into a normal dict using the dict() constructor, but this feels dirty
> to me.



-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to