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


Groups > comp.lang.python > #81766 > unrolled thread

Re: Setting default_factory of defaultdict to key

Started byTim Chase <python.list@tim.thechases.com>
First post2014-12-01 12:25 -0600
Last post2014-12-01 12:25 -0600
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: Setting default_factory of defaultdict to key Tim Chase <python.list@tim.thechases.com> - 2014-12-01 12:25 -0600

#81766 — Re: Setting default_factory of defaultdict to key

FromTim Chase <python.list@tim.thechases.com>
Date2014-12-01 12:25 -0600
SubjectRe: Setting default_factory of defaultdict to key
Message-ID<mailman.16462.1417458574.18130.python-list@python.org>
On 2014-12-01 13:05, 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?
> 
> 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)

You could subclass it:

  class MyDefaultDict(defaultdict):
    def __missing__(self, key):
      #self[key] = key  # if you actually want it in the dict
      return key


You might also have to override the __contains__ method to always
return True if you want

  value_not_in_dict = 42
  my_default_dict = MyDefaultDict(int)
  if value_not_in_dict in my_default_dict:
    this_branch_would_always_happen()
  else:
    this_branch_should_never_happen

You'd also have weird behaviors with iterators as they'd only ever
iterate over things that were in the dict.

-tkc

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web