I am running Python 2.7.10.
I would like to have a dictionary return the value stored at a particular key in case of missing item. For example, something like that:
myD = dict(...)
return myD[key] if key in myD else myD[defaultKey]
Just to make sure it is clear, I want to call myD[key] and have the right value returned without the extra if...else in my code...
This isn't quite what defaultdict does (since it takes a function to call as a default) and not quite what dict.setdefault() does, and myD.get(key, ???) does not seem to help either. I probably should inherit from dict or defaultdict and overload __init__() and missing() methods, but I could not come up with a good way to do this.
dict.getwon't do that; if you want to know how you could write your own, look at docs.python.org/2/library/… and implement__getitem__accordingly. But where shoulddefaultKeycome from (is it a parameter? An attribute of the class, or of the instance?)defaultKeyis param at initialization, that the instance should store as an attribute__[get/set/del]item__,__iter__and__len__, plus your custom__init__for the default key-value pair).defaultdict, and just overriding__getitem__, leaving same functionality everywhere else...