473,383 Members | 1,984 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,383 software developers and data experts.

Fun transformation problem

A guy in the office has come up with this interesting transformation
problem. We have a solution but I'm sure there's a neater, more 'pythonic'
approach.

I thought this might appeal to some here:

I want a function to convert a list of tuples into a hierarchy of
dictionaries. *Let me first demonstrate with an example:
lstA = [(1, 2, 3), (1, 3, 4), (2, 5, 6)]
dctA = fncA(lstA)
print dctA {1: {2: 3, 3: 4}, 2: {5: 6}}
I essentially want the definition to fncA. *Here is another example:
lstA = [(1, 2, 3, 4) ,(3, 4, 5, 6), (3, 4, 6, 7), (3, 4, 6, 8), (3, 4, 5, 1), (3, 4, 7, 9)] dctA = fncA(lstA)
print dctA {1: {2: {3: 4}}, 3: {4: {5: 1, 6: 8, 7: 9}}}


Each tuple in the original list must be unique after the last value is
excluded (since these values are used to form the "hierarchical key".

I have written a function, which seems to work but looks very cumbersome.
Could anyone point me to a simpler solution?

Dale Strickland-Clark
Riverhall Systems
Jul 18 '05 #1
5 1277
Dale Strickland-Clark wrote:
A guy in the office has come up with this interesting transformation
problem. We have a solution but I'm sure there's a neater, more 'pythonic'
approach.

I thought this might appeal to some here:

I want a function to convert a list of tuples into a hierarchy of
dictionaries. Let me first demonstrate with an example:

lstA = [(1, 2, 3), (1, 3, 4), (2, 5, 6)]
dctA = fncA(lstA)
print dctA
{1: {2: 3, 3: 4}, 2: {5: 6}}
I essentially want the definition to fncA. Here is another example:

lstA = [(1, 2, 3, 4) ,(3, 4, 5, 6), (3, 4, 6, 7), (3, 4, 6, 8), (3, 4,
5, 1), (3, 4, 7, 9)]
dctA = fncA(lstA)
print dctA


{1: {2: {3: 4}}, 3: {4: {5: 1, 6: 8, 7: 9}}}
Each tuple in the original list must be unique after the last value is
excluded (since these values are used to form the "hierarchical key".

I have written a function, which seems to work but looks very cumbersome.
Could anyone point me to a simpler solution?

Dale Strickland-Clark
Riverhall Systems


The following:

def transform(l):
d = {}

for t in l:
c = d
for e in t[:-2]:
c = c.setdefault(e, {})
c[t[-2]] = t[-1]

return d

seems clear enough for me.

with the best regards,
anton.
Jul 18 '05 #2
This is what I came up with. It's recursive, so it could get you into
trouble with longer lists, but hey, it's late at night and it'll do
for now :-)

def g(d, lst):
head = lst[0]
tail = lst[1:]
if not tail:
return head
else:
d[head] = g(d.get(head, {}), tail)
return d

def f(lst):
d = {}
for xs in lst:
d = g(d, xs)
return d

Cheers,

Tim

On Thu, 26 Aug 2004 18:20:23 +0400, anton muhin <an********@rambler.ru> wrote:


Dale Strickland-Clark wrote:
A guy in the office has come up with this interesting transformation
problem. We have a solution but I'm sure there's a neater, more 'pythonic'
approach.

I thought this might appeal to some here:

I want a function to convert a list of tuples into a hierarchy of
dictionaries. Let me first demonstrate with an example:

>lstA = [(1, 2, 3), (1, 3, 4), (2, 5, 6)]
>dctA = fncA(lstA)
>print dctA


{1: {2: 3, 3: 4}, 2: {5: 6}}
I essentially want the definition to fncA. Here is another example:

>lstA = [(1, 2, 3, 4) ,(3, 4, 5, 6), (3, 4, 6, 7), (3, 4, 6, 8), (3, 4,


5, 1), (3, 4, 7, 9)]
>dctA = fncA(lstA)
>print dctA


{1: {2: {3: 4}}, 3: {4: {5: 1, 6: 8, 7: 9}}}
Each tuple in the original list must be unique after the last value is
excluded (since these values are used to form the "hierarchical key".

I have written a function, which seems to work but looks very cumbersome.
Could anyone point me to a simpler solution?

Dale Strickland-Clark
Riverhall Systems


The following:

def transform(l):
d = {}

for t in l:
c = d
for e in t[:-2]:
c = c.setdefault(e, {})
c[t[-2]] = t[-1]

return d

seems clear enough for me.

with the best regards,
anton.
--
http://mail.python.org/mailman/listinfo/python-list

Jul 18 '05 #3
Thanks to everyone for your replies. Very interesting.

It is not too embarrasing to admit that these were better than we'd come
up with.

My colleague will be getting to grips with a newsreader in the near future
and may be along later to express his own gratitude.

--
Dale Strickland-Clark
Riverhall Systems Ltd, www.riverhall.co.uk
Jul 18 '05 #4
On Fri, Aug 27, 2004 at 09:20:18AM +0000, Dale Strickland-Clak wrote:
Thanks to everyone for your replies. Very interesting.

It is not too embarrasing to admit that these were better than we'd come
up with.

My colleague will be getting to grips with a newsreader in the near future
and may be along later to express his own gratitude.


FYI, that goofy dictionary thing you're building is called a 'trie'.
--
John Lenton (jo**@grulic.org.ar) -- Random fortune:
No one can guarantee the actions of another.
-- Spock, "Day of the Dove", stardate unknown

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.5 (GNU/Linux)

iD8DBQFBL6rkgPqu395ykGsRAnr1AJ4+U/wTqh8XHZYZaDpYphIVBDqpAACeLLvP
/mkmNreb9+mo3WVTFsCDbNM=
=SKUd
-----END PGP SIGNATURE-----

Jul 18 '05 #5
John Lenton <jo**@grulic.org.ar> wrote:
FYI, that goofy dictionary thing you're building is called a 'trie'.


And in some applications it may be handy to be able to construct the
trie piece by piece, or to add entries to it. (BTW, am I wrong in
thinking that tries in general aren't restricted to having all leaf
nodes at the same level as the examples in this all do? Not that I'm
complaining, since I'm not going to handle that general case either!)
So I'll start with a function to add a single leaf to a trie:

def add2trie(car, cdr, trie):
if len(cdr) == 1:
trie[car] = cdr[0]
else:
if not trie.has_key(car):
trie[car] = {}
add2trie(cdr[0], cdr[1:], trie[car])

....and then the requested function is trivial:

def f(lstlst):
trie = {}
for lst in lstlst:
add2trie(lst[0], lst[1:], trie)
return trie

car and cdr are intrusions from you-can-guess-where that suggested
themselves in the first hack which had 'way too many occurences of lst[0]
in it.

<digression>

BTW, the first sketch (which I decided I didn't like for its
unnecessary rebinding of existing subtries) could have made good use of
conditional assignment (sorry, it just keeps coming up as I skim
through the backlog today). It would have gone something like...

def add2trie(lst, trie):
trie[lst[0]] = (if len(lst) == 2: lst[1]
else: add2trie(lst[1:], trie.get(lst[0], {}))
return trie

Obviously this is untested code, and to be honest I don't much like
this form when it has to spread across lines like that. OTOH, it's an
amusing example, since it uses within the general conditional
expression one of Python's existing special-case hacks that wouldn't be
necessary (though it might still be handy) if Python had conditional
expressions. :-)

</digression>

--
Vs lbh pna ernq guvf, lbh'er va ivbyngvba bs
gur Qvtvgny Zvyyraavhz Pbclevtug Npg. -- anon.
Jul 18 '05 #6

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

Similar topics

0
by: Sergio del Amo | last post by:
Hi, I use the xslt functions provided by php. I am running in my computer the package xampp(www.apachefriends.org) which includes php/apache/mysql .. In this package the php includes the sablotron...
3
by: pradeep gummi | last post by:
I have an XML FILE that is to be converted to Plain Text using an XSL file. Since I just want plain text, I do not want to set any root element during transformation.And if I do not any root...
7
by: CK | last post by:
Hello, I have the 60 MB XML string and I am coding a program in Visual Basic to run a XSL transformation on it. Currently, I'm using the Microsoft standard MSXML 2.0 to create a DOM document, load...
8
by: Will | last post by:
I was thrust into XML about 2 weeks ago and don't know much yet. From another department in the corp I am receiving an XML file which concatenates nodes all on one line i.e....
4
by: Mike Conmackie | last post by:
Hi Folks, I've probably omitted something very basic but I have no idea what it might be. The results of my transformation _should_ be an xml file but all I get is the xml declaration...
1
by: Ali Asghar | last post by:
Hi, Please I need help.I have a problem of client side XSL transformation. I sent the XML and the XSL to the client in XML data islands. Using the transform Node method the HTML is returned....
6
by: Jain, Pranay Kumar | last post by:
Hi All, We have created a simple application that takes a dataset and generates the data in Excel schema format. It uses an xslt file to do the transformation for excel 2002 and so on. We are...
2
by: TomekR | last post by:
Hello ! I was developing xslt sheet lately and - experimenting - I made mistake resulting in that, the effect of the transformation is not well-formed xml document. I made these tests using...
0
by: Hugo Ferreira | last post by:
Hi all, I'm having a problem here, to which I hope someone to be able to help me :) I need to apply a XSLT transformation to the output of all my ASPX webpages. I've recently found the tag...
4
by: =?Utf-8?B?REZC?= | last post by:
Within an XSLT transformation, I'm trying to switch the default namespace within a section of the generated XML document to a shared namespace. This way, the content of this section does not have...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...

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.