473,657 Members | 2,566 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Playing with dictionaries

Hi,

Suppose I have a dictionary containg nested dictionaries. Something
like this:
pprint.pprint(d ataset) {'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.experime nter'
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
Jul 18 '05 #1
5 1405
In article <10************ *************@p osting.google.c om>,
ro*****@dealmei da.net (Roberto A. F. De Almeida) wrote:
Suppose I have a dictionary containg nested dictionaries. Something
like this:
pprint.pprint(d ataset) {'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.experime nter'
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(d ataset,prefix=' '):
for key in dataset:
if dataset[key] is None:
dataset[key] = prefix + key
elif isinstance(data set[key], dict):
makehierarchy(d ataset[key], prefix + key + ".")
else:
raise ValueError, "Unexpected data type in makehierarchy"
makehierarchy(d ataset,'dataset ')
pprint.pprint(d ataset)

{'casts': {'experimenter' : 'casts.experime nter',
'location': {'latitude': 'casts.location .latitude',
'longitude': 'casts.location .longitude'},
'time': 'casts.time',
'xbt': {'depth': 'casts.xbt.dept h',
'temperature': 'casts.xbt.temp erature'}},
'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
Jul 18 '05 #2
[Roberto A. F. De Almeida]
Suppose I have a dictionary containg nested dictionaries. Something
like this:
pprint.pprint(d ataset) {'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.experime nter'
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.dept h', 'casts.xbt.temp erature', 'casts.experime nter',
'casts.location .latitude', 'casts.location .longitude', 'casts.time',
'z.maps.lat', 'z.maps.lon', 'z.array.z', 'catalog_number ']
Raymond Hettinger
Jul 18 '05 #3
In article <ep************ *************** *@news.service. uci.edu>,
David Eppstein <ep******@ics.u ci.edu> wrote:
def makehierarchy(d ataset,prefix=' '):
for key in dataset:
if dataset[key] is None:
dataset[key] = prefix + key
elif isinstance(data set[key], dict):
makehierarchy(d ataset[key], prefix + key + ".")
else:
raise ValueError, "Unexpected data type in makehierarchy"
makehierarchy(d ataset,'dataset ')
Sorry, cut-and-paste error here -- updated the live code and forgot to
update the copy in my posting. That should be makehierarchy(d ataset).
pprint.pprint(d ataset)

{'casts': {'experimenter' : 'casts.experime nter',
'location': {'latitude': 'casts.location .latitude',
'longitude': 'casts.location .longitude'},
'time': 'casts.time',
'xbt': {'depth': 'casts.xbt.dept h',
'temperature': 'casts.xbt.temp erature'}},
'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
Jul 18 '05 #4
Roberto A. F. De Almeida wrote:
Suppose I have a dictionary containg nested dictionaries. Something
like this:
pprint.pprint(d ataset) {'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.experime nter'
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__(sel f, name):
return Dict(name, self)
def __str__(self):
if self.parent and self.parent.par ent:
return ".".join((str(s elf.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

Jul 18 '05 #5
Hi, guys.

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

Roberto
Jul 18 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
2194
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 x in range(10):
0
1359
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 fairly simple (searching/organizing large boardgame databases) but use a lot of memory (1-6GB). The memory is mostly used for simple structures like trees or relations. Typically there will be a few large dictionaries and many small...
8
2614
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 = {}
3
2366
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 a string bsddb requires that both the key,value are string. shelve does support values being object but not the keys. Is there any
210
10433
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 I am missing that feature. Maybe there is something wrong with my programming style, but I rather think it is generally useful. I fully agree with the following posting where somebody complains why so very basic and useful things are not part...
2
2617
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 useful for storing constants especially. Generally I find myself either needing to retrieve the values of constants in an iterative way (as in my contrived example below). Perhaps even more frequent is given one value is to look up the matching...
8
1742
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
1
165
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 re-run.... fun learning with python... Edwin -----Original Message----- From: Madari, Edwin Sent: Thursday, August 14, 2008 9:24 PM
14
1809
by: cnb | last post by:
Are dictionaries the same as hashtables?
0
8392
marktang
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8732
jinu1996
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
7324
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6163
isladogs
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5632
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4151
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4302
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2726
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 we have to send another system
2
1953
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.