I need a dict that inherits its mappings
tjreedy at udel.edu
Thu Jun 25 14:21:18 EDT 2009
> I need a dict-like object that, if it doesn't contain a key, will
> return the value from a "parent" object. Is there an easy way to do
> this so I don't have to define __getitem__ and __contains__ and others
> that I haven't even thought of yet? Here's a use case, if you're
> en_GB['bonnet']='part of your car'
> print en_US['bonnet'] # prints 'part of your car'
> en_US['bonnet']='a type of hat'
> print en_US['bonnet'] # prints 'a type of hat'
> print en_GB['bonnet'] # prints 'part of your car'
For that specific case:
try: return en_US[key]
except KeyError: return en_GB[key]
def make_lookup_with_backup(d1, d2):
try: return d1[key]
except KeyError: return d2[key]
Terry Jan Reedy
More information about the Python-list