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]> 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].
> 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/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/CAKgW%3D6K_KB7jSkKxZ5%3DZGkY9kNZ_JGaGRGGza9S-v-AK4rD%2BWA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.