I need a dict that inherits its mappings

S

samwyse

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'
 
T

Tobias Weber

samwyse said:
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

What's wrong with that?

You can subclass collections.defaultdict and override __missing__
 
T

Terry Reedy

samwyse said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,201
Messages
2,571,052
Members
47,656
Latest member
rickwatson

Latest Threads

Top