Setting default_factory of defaultdict to key

Ian Kelly ian.g.kelly at gmail.com
Mon Dec 1 13:11:54 EST 2014


On Mon, Dec 1, 2014 at 11:05 AM, Larry Martell <larry.martell at gmail.com> wrote:
> Is there a way to set the default_factory of defaultdict so that
> accesses to undefined keys get to set to the key?
>
> i.e. if d['xxx'] were accessed and there was no key 'xxx' then
> d['xxx'] would get set to 'xxx'
>
> I know I can define a function with lambda for the default_factory,
> but I don't see how to access the key. I tried:
>
> d = defaultdict(lambda: key)
>
> But that did not work.

Not with defaultdict, but you can subclass dict and provide a
__missing__ method directly, which is passed the key. This is
basically all that defaultdict does.



More information about the Python-list mailing list