Inheriting dictionary
Simon Forman
sajmikins at gmail.com
Tue Aug 18 18:08:11 EDT 2009
On Aug 18, 3:44 pm, Pavel Panchekha <pavpanche... at gmail.com> wrote:
> I want a dictionary that will transparently "inherit" from a parent
> dictionary. So, for example:
>
> """
> a = InheritDict({1: "one", 2: "two", 4: "four"})
> b = InheritDict({3: "three", 4: "foobar"}, inherit_from=a)
>
> a[1] # "one"
> a[4] # "four"
> b[1] # "one"
> b[3] # "three"
> b[4] # "foobar"
> """
>
> I've written something like this in Python already, but I'm wondering
> if something like this already exists, preferably written in C, for
> speed.
I would consider something like the following:
a = {1: "one", 2: "two", 4: "four"}
b = {3: "three", 4: "foobar"}
from functools import partial
def getter(first, second, key):
try:
return first(key)
except KeyError:
return second(key)
f = partial(getter, b.__getitem__, a.__getitem__)
# Or, if you know you'll be getting a lot of KeyErrors, you
# can use get() instead of __getitem__().
def getter1(first, second, key, sentinel=None):
item = first(key, sentinel)
if item is sentinel:
item = second(key)
return item
g = partial(getter1, b.get, a.__getitem__)
HTH,
~Simon
More information about the Python-list
mailing list