Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #81766
| Date | 2014-12-01 12:25 -0600 |
|---|---|
| From | Tim Chase <python.list@tim.thechases.com> |
| Subject | Re: Setting default_factory of defaultdict to key |
| References | <CACwCsY7sCi51Aq9z3vbSohG-gq-xHyo_=jXzS04FUVy1b8F5Qw@mail.gmail.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.16462.1417458574.18130.python-list@python.org> (permalink) |
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
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: Setting default_factory of defaultdict to key Tim Chase <python.list@tim.thechases.com> - 2014-12-01 12:25 -0600
csiph-web