Playing with dictionaries

  • Thread starter Roberto A. F. De Almeida
  • Start date
R

Roberto A. F. De Almeida

Hi,

Suppose I have a dictionary containg nested dictionaries. Something
like this:
{'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?

Thanks,

Roberto
 
D

David Eppstein

Suppose I have a dictionary containg nested dictionaries. Something
like this:
{'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"
{'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'}}}
 
R

Raymond Hettinger

[Roberto A. F. De Almeida]
Suppose I have a dictionary containg nested dictionaries. Something
like this:
{'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?

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


['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
 
D

David Eppstein

David Eppstein said:
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"

Sorry, cut-and-paste error here -- updated the live code and forgot to
update the copy in my posting. That should be makehierarchy(dataset).
 
P

Peter Otten

Roberto said:
Suppose I have a dictionary containg nested dictionaries. Something
like this:
{'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
 
R

Roberto A. F. De Almeida

Hi, guys.

Thanks for the all the answers and the valuable insights. I mixed them
all and got what I want. :)

Roberto
 

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

No members online now.

Forum statistics

Threads
474,164
Messages
2,570,898
Members
47,439
Latest member
shasuze

Latest Threads

Top