Playing with dictionaries

Peter Otten __peter__ at web.de
Mon Sep 22 21:04:43 CEST 2003


Roberto A. F. De Almeida wrote:

> Suppose I have a dictionary containg nested dictionaries. Something
> like this:
> 
>>>> pprint.pprint(dataset)
> {'casts': {'experimenter': None,
>            'location': {'latitude': None,
>                         'longitude': None},
>            'time': None,
>            'xbt': {'depth': None,
>                    'temperature': None}},
>  'catalog_number': None,
>  'z': {'array': {'z': None},
>        'maps': {'lat': None,
>                 'lon': None}}}
> 
> I want to assign to the values in the dictionary the hierarchy of keys
> to it. For example:
> 
>>>> dataset['casts']['experimenter'] = 'casts.experimenter'
>>>> dataset['z']['array']['z'] = 'z.array.z'
> 
> Of course I would like to do this automatically, independent of the
> structure of the dictionary. Is there an easy way to do it?

class Dict:
    def __init__(self, name=None, parent=None):
        self.name = name
        self.parent = parent
    def __getitem__(self, name):
        return Dict(name, self)
    def __str__(self):
        if self.parent and self.parent.parent:
            return ".".join((str(self.parent), self.name))
        elif self.name is not None:
            return self.name
        return "I warned you"


d = Dict()
print d['casts']
print d['casts']['experimenter']
print d['casts']['location']['latitude']
#print d # do not uncomment

Seems to work :-)
I doubt that anybody can come up with something more automatic or more
independent of the structure of the dictionary than the above. And it was
easy, too, wasn't it?

Peter





More information about the Python-list mailing list