Nice! I thought there had to be a better way. Hopefully we are using this
in SparseMatrix.
On Monday, November 27, 2017 at 3:00:06 PM UTC-6, Aaron Meurer wrote:
>
> That's a generalized version of defaultdict. For just returning the
> key, you can just use
>
> class default_to_key(dict):
> def __missing__(self, key):
> return key
>
> Worth noting is a potentially important difference between subclassing
> dict and defaultdict: when you lookup a missing entry in a
> defaultdict, it gets saved for future lookups
>
> >>> lookup = KeyAwareDefaultDict(Id)
> >>> lookup[x]
> x
> >>> lookup
> defaultdict(Lambda(_x, _x), {x: x})
>
> This is wasteful when your lookup function is fast and stateless
> (always returns the same output for a given input). If it's not fast
> or not stateless, defaultdict is better, but for Id, I think the dict
> solution might be preferred.
>
> Aaron Meurer
>
> On Mon, Nov 27, 2017 at 9:25 AM, Chris Smith <[email protected]
> <javascript:>> wrote:
> > Am I missing some obvious way to have a default dict that returns the
> key if
> > it is not present? If not, I found this by googling:
> >
> > from collections import defaultdict
> >
> > class KeyAwareDefaultDict(defaultdict):
> > def __missing__(self, key):
> > if self.default_factory is None:
> > raise KeyError(key)
> > self[key] = value = self.default_factory(key)
> > return value
> >
> >>>> lookup = KeyAwareDefaultDict(Id)
> >>>> lookup[x]
> > x
> >>>> lookup[x] = y; lookup[x]
> > y
> >
> >
> > --
> > You received this message because you are subscribed to the Google
> Groups
> > "sympy" group.
> > To unsubscribe from this group and stop receiving emails from it, send
> an
> > email to [email protected] <javascript:>.
> > To post to this group, send email to [email protected]
> <javascript:>.
> > Visit this group at https://groups.google.com/group/sympy.
> > To view this discussion on the web visit
> >
> https://groups.google.com/d/msgid/sympy/945624cb-edc4-4804-85d7-36bd3e41a9b6%40googlegroups.com.
>
>
> > For more options, visit https://groups.google.com/d/optout.
>
--
You received this message because you are subscribed to the Google Groups
"sympy" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at https://groups.google.com/group/sympy.
To view this discussion on the web visit
https://groups.google.com/d/msgid/sympy/363a83d3-e6ca-4264-b587-f8286e9c3a30%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.