Playing with dictionaries

David Eppstein eppstein at ics.uci.edu
Mon Sep 22 13:57:52 EDT 2003


In article <10c662fe.0309220907.a84bea5 at posting.google.com>,
 roberto at dealmeida.net (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?

def makehierarchy(dataset,prefix=''):
   for key in dataset:
      if dataset[key] is None:
         dataset[key] = prefix + key
      elif isinstance(dataset[key], dict):
         makehierarchy(dataset[key], prefix + key + ".")
      else:
         raise ValueError, "Unexpected data type in makehierarchy"

>>> makehierarchy(dataset,'dataset')
>>> pprint.pprint(dataset)
{'casts': {'experimenter': 'casts.experimenter',
           'location': {'latitude': 'casts.location.latitude',
                        'longitude': 'casts.location.longitude'},
           'time': 'casts.time',
           'xbt': {'depth': 'casts.xbt.depth',
                   'temperature': 'casts.xbt.temperature'}},
 'catalog_number': 'catalog_number',
 'z': {'array': {'z': 'z.array.z'},
       'maps': {'lat': 'z.maps.lat', 'lon': 'z.maps.lon'}}}

-- 
David Eppstein                      http://www.ics.uci.edu/~eppstein/
Univ. of California, Irvine, School of Information & Computer Science




More information about the Python-list mailing list