Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #81765

Re: Setting default_factory of defaultdict to key

References <CACwCsY7sCi51Aq9z3vbSohG-gq-xHyo_=jXzS04FUVy1b8F5Qw@mail.gmail.com> <547CB12C.3010502@stoneleaf.us>
Date 2014-12-01 13:29 -0500
Subject Re: Setting default_factory of defaultdict to key
From Larry Martell <larry.martell@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.16461.1417458574.18130.python-list@python.org> (permalink)

Show all headers | View raw


On Mon, Dec 1, 2014 at 1:19 PM, Ethan Furman <ethan@stoneleaf.us> wrote:
> On 12/01/2014 10:05 AM, Larry Martell wrote:
>>
>> Is there a way to set the default_factory of defaultdict so that
>> accesses to undefined keys get to set to the key?
>
> You need to subclass and modify __missing__ to actually pass along the key:
>
> --> class defaultdictkey(defaultdict):
> ...   def __missing__(self, key):
> ...     self[key] = self.default_factory(key)
> ...     return self[key]
> ...
>
> and in action:
>
> --> huh = defaultdictkey(lambda k: k)
> --> huh
> defaultdict(<function <lambda> at 0x7fe1305de3f0>, {})
> --> huh['x']
> 'x'
> --> huh['x']
> 'x'
> --> huh.get('y')
> --> huh['y']
> 'y'
> --> huh.get('y')
> 'y'


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

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: Setting default_factory of defaultdict to key Larry Martell <larry.martell@gmail.com> - 2014-12-01 13:29 -0500

csiph-web