default behavior

Stefan Schwarzer sschwarzer at sschwarzer.net
Sat Aug 7 06:41:12 EDT 2010


On 2010-07-31 05:47, Steven D'Aprano wrote:
> On Fri, 30 Jul 2010 08:34:52 -0400, wheres pythonmonks wrote:
> It does re-use the same underlying data.
> 
> >>> from collections import defaultdict as dd
> >>> x = dd(list)
> >>> x[1].append(1)
> >>> x
> defaultdict(<type 'list'>, {1: [1]})
> >>> y = dict(x)
> >>> x[1].append(42)
> >>> y
> {1: [1, 42]}

One thing to keep in mind: dict(some_defaultdict) doesn't
store a reference to the defaultdict; instead it makes a
shallow copy, so key/value pairs added _after_ the "cast"
aren't included in the new dict:

>>> y[2] = 17
>>> y
{1: [1, 42], 2: 17}
>>> x
defaultdict(<type 'list'>, {1: [1, 42]})

Stefan



More information about the Python-list mailing list