0

I have following dictionary

mydict = { 'name': "Hello",
           'address': { 'place': 'India',
                        'street': {
                                   'One': 'Street one', 'Two': 'Street Two' }
                       },
            'Job': 'Sleep' }

So I can access the value of Street one like mydict['address']['street']['One']

Now I am thinking of simplifying this like this

I have another dictionary like below

dict_map = {'Name': ['name'],
            'AddressOne': ['address','street','One'] }

Is there any way I can directly access the element 'One' using dict_map['AddressOne']

Thanks ~S

user2677279
  • 127
  • 3
  • 10

1 Answers1

0

There are really many ways to do this. For example:

class DictMapper(object):

    def __init__(self, d, d_map):
        self.d = d
        self.dict_map = d_map

    def __getitem__(self, item):
        return reduce(lambda res, path: res[path], self.dict_map[item], self.d)

Usage:

dm = DictMapper(mydict, dict_map)
print dm["AddressOne"]
ShabashP
  • 578
  • 2
  • 10