I need a dict that inherits its mappings

Terry Reedy tjreedy at udel.edu
Thu Jun 25 14:21:18 EDT 2009


samwyse wrote:
> 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
> confused:
> 
> en_GB=mydict()
> en_US=mydict(en_GB)
> 
> 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:

def lookup(key):
   try: return en_US[key]
   except KeyError: return en_GB[key]

More generally,

def make_lookup_with_backup(d1, d2):
   def _l(key):
     try: return d1[key]
     except KeyError: return d2[key]
   return _

Terry Jan Reedy




More information about the Python-list mailing list