Setting default_factory of defaultdict to key

Tim Chase python.list at tim.thechases.com
Mon Dec 1 13:25:53 EST 2014


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





More information about the Python-list mailing list