how to make a default dict that returns Id of key?

31 views
Skip to first unread message

Chris Smith

unread,
Nov 27, 2017, 11:25:06 AM11/27/17
to sympy
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

Aaron Meurer

unread,
Nov 27, 2017, 4:00:06 PM11/27/17
to sy...@googlegroups.com
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
> --
> 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 sympy+un...@googlegroups.com.
> To post to this group, send email to sy...@googlegroups.com.
> 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.

Chris Smith

unread,
Nov 28, 2017, 4:39:26 PM11/28/17
to sympy
Nice! I thought there had to be a better way. Hopefully we are using this in SparseMatrix.
Reply all
Reply to author
Forward
0 new messages