Playing with dictionaries

Raymond Hettinger vze4rx4y at verizon.net
Mon Sep 22 14:07:05 EDT 2003


[Roberto A. F. De Almeida]
> 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?



>>> def f(d):
    for k, v in d.iteritems():
        if v is None:
            yield k
        else:
            for name in f(v):
                yield k + '.' + name



>>> list(f(d))
['casts.xbt.depth', 'casts.xbt.temperature', 'casts.experimenter',
'casts.location.latitude', 'casts.location.longitude', 'casts.time',
'z.maps.lat', 'z.maps.lon', 'z.array.z', 'catalog_number']


Raymond Hettinger






More information about the Python-list mailing list