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
<https://stackoverflow.com/questions/10524142/python-dictionary-return-requested-key-if-value-does-not-exist>
:
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.