Hi,
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?
Thanks,
Roberto 5 1393
In article <10*************************@posting.google.com> , ro*****@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
[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
In article <ep****************************@news.service.uci.e du>,
David Eppstein <ep******@ics.uci.edu> wrote: 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')
Sorry, cut-and-paste error here -- updated the live code and forgot to
update the copy in my posting. That should be makehierarchy(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
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
Hi, guys.
Thanks for the all the answers and the valuable insights. I mixed them
all and got what I want. :)
Roberto This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Kerry Neilson |
last post by:
Hi,
Really hung up on this one. I'm trying to get all the fields of a
dictionary to be unique for each class:
class A {
my_dict =
dict_entry = { 'key1':0, 'key2':0 }
__init__(self):
for...
|
by: Till Plewe |
last post by:
Is there a way to speed up killing python from within a python program?
Sometimes shutting down takes more than 10 times as much time as the actual
running of the program.
The programs are...
|
by: Frohnhofer, James |
last post by:
My initial problem was to initialize a bunch of dictionaries at the start of a
function.
I did not want to do
def fn():
a = {}
b = {}
c = {}
. . .
z = {}
|
by: Shivram U |
last post by:
Hi,
I want to store dictionaries on disk. I had a look at a few modules
like bsddb, shelve etc. However would it be possible for me to do the
following
hash = where the key is an int and not...
|
by: Christoph Zwerschke |
last post by:
This is probably a FAQ, but I dare to ask it nevertheless since I
haven't found a satisfying answer yet: Why isn't there an "ordered
dictionary" class at least in the standard list? Time and again...
| |
by: David Pratt |
last post by:
Hi. I like working with lists of dictionaries since order is preserved
in a list when I want order and the dictionaries make it explicit what
I have got inside them. I find this combination very...
|
by: placid |
last post by:
Hi all,
Just wondering if anyone knows how to pop up the dialog that windows
pops up when copying/moving/deleting files from one directory to
another, in python ?
Cheers
|
by: Edwin.Madari |
last post by:
by the way, iterating over bar will throw KeyError if that key does not exist in foo. to see that in action, simply set another key in bar after copy.deepcopy stmt in this example..
bar = 0
and...
|
by: cnb |
last post by:
Are dictionaries the same as hashtables?
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers,...
| |
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The...
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...
| |