Setting default_factory of defaultdict to key

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


On Mon, Dec 1, 2014 at 11:29 AM, Larry Martell <larry.martell at gmail.com> wrote:
> I spoke too soon:
>
>>>> class defaultdictkey(defaultdict):
> ...  def __missing__(self, key):
> ...   self[key] = self.default_factory(key)
> ...
>>>> x = defaultdictkey(lambda k: k)
>>>> print x['aaa']
> None
>>>> print x['aaa']
> aaa
>>>> a = x['qqq']
>>>> print a
> None

You need to also return the value from __missing__.



More information about the Python-list mailing list