default behavior

Peter Otten __peter__ at web.de
Fri Jul 30 08:33:49 EDT 2010


wheres pythonmonks wrote:

> Instead of defaultdict for hash of lists, I have seen something like:
> 
> 
> m={}; m.setdefault('key', []).append(1)
> 
> Would this be preferred in some circumstances?

In some circumstances, sure. I just can't think of them at the moment. 
Maybe if your code has to work in Python 2.4.

> Also, is there a way to upcast a defaultdict into a dict?  

dict(some_defaultdict)

> I have also
> heard some people use exceptions on dictionaries to catch key
> existence, so passing in a defaultdict (I guess) could be hazardous to
> health.  Is this true?

A problem could arise when you swap a "key in dict" test with a 
"try...except KeyError". This would be an implementation detail for a dict 
but affect the contents of a defaultdict:

>>> from collections import defaultdict
>>> def update(d):
...     for c in "abc":
...             try: d[c]
...             except KeyError: d[c] = c
...
>>> d = defaultdict(lambda:"-")
>>> update(d)
>>> d
defaultdict(<function <lambda> at 0x7fd4ce32a320>, {'a': '-', 'c': '-', 'b': 
'-'})
>>> def update2(d):
...     for c in "abc":
...             if c not in d:
...                     d[c] = c
...
>>> d = defaultdict(lambda:"-")
>>> update2(d)
>>> d
defaultdict(<function <lambda> at 0x7fd4ce32a6e0>, {'a': 'a', 'c': 'c', 'b': 
'b'})

Peter




More information about the Python-list mailing list