Python Forum
Chain object that have parent child relation..
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Chain object that have parent child relation..
#1
Question 
Hi everyone,

I have some data in a DB that have a parent properties

name|parent

John|Null
David|John
Grunt|David
Jade|John
This give this ~hierarchy
John
    - David
        - Grunt
    - Jade
I would like to create a python object of those relations (the tree might be deeper ! :) )
like something like
['John', ['David', ['Grunt', None]],['Jade', None]]
So I'm losing my mind as I don't find and efficient way..

of course if you have another format for the outputed Python object (than chain of list) I'm all ears too :)

Thanks
[Image: NfRQr9R.jpg]
Reply
#2
Would that not look like this?
names = {
    "John": {
        "David": {
            "Grunt": None
        },
        "Jade": None
    }
}
Sig:
>>> import this

The UNIX philosophy: "Do one thing, and do it well."

"The danger of computers becoming like humans is not as great as the danger of humans becoming like computers." :~ Konrad Zuse

"Everything should be made as simple as possible, but not simpler." :~ Albert Einstein
Reply
#3
@rob101

The output can be as a dictbut I doubt it's more quicker than list or tuples ?

and how could I generate this dict from the DB @rob101 ?
[Image: NfRQr9R.jpg]
Reply
#4
I don't think that the speed difference between the two will be even noticeably. For me, I find the dictionary more "human readable". As for building that from a DB; there's always a way.
Sig:
>>> import this

The UNIX philosophy: "Do one thing, and do it well."

"The danger of computers becoming like humans is not as great as the danger of humans becoming like computers." :~ Konrad Zuse

"Everything should be made as simple as possible, but not simpler." :~ Albert Einstein
Reply
#5
You could do it like this
>>> from collections import defaultdict
>>> builder = defaultdict(dict)
>>> pairs = [('John', 'Null'), ('David', 'John'), ('Grunt','David'), ('Jade', 'John')]
>>> for node, parent in pairs:
...     builder[parent][node] = builder[node]
... 
>>> print(builder['Null'])
{'John': {'David': {'Grunt': {}}, 'Jade': {}}}
>>> 
SpongeB0B and rob101 like this post
« We can solve any problem by introducing an extra level of indirection »
Reply
#6
@Gribouillis Thank you !

This is working great, and I discover defaultdict that is a relief to work with dict :)

now with
{'John': {'David': {'Grunt': {}}, 'Jade': {}}}
I would like to print a hierarchy
John
    - David
        - Grunt
    - Jade
The ultimate goal is to great an html output ~like this

<ul>
    
    <li>John
        <ul>
            <li>David
                <ul>
                    <li>Grunt</li>
                </ul>
            </li>
            <li>Jade</li>
          </ul>
    </li>
      </ul>
[Image: NfRQr9R.jpg]
Reply
#7
(Dec-11-2023, 10:01 AM)SpongeB0B Wrote: I would like to print a hierarchy
What have you tried? Post your code!
« We can solve any problem by introducing an extra level of indirection »
Reply
#8
def looper(k,v):
	if v == {}:
		print(str(k) + ' |')
	else:
		print(' ' + str(k) + ' +')
		for key,val in v.items():
			looper(key,val)


for k,v in builder['Null'].items():
	looper(k,v)
This is just a test :) but I realize That I might need Generator instead..
[Image: NfRQr9R.jpg]
Reply
#9
(Dec-11-2023, 10:01 AM)SpongeB0B Wrote: The ultimate goal is to great an html output ~like this
I think you should generate unformatted html code, then process it with bs4.BeautifulSoup.prettify() Custom formatters can be created to alter the result of prettify()
« We can solve any problem by introducing an extra level of indirection »
Reply
#10
(Dec-11-2023, 09:19 PM)Gribouillis Wrote: I think you should generate unformatted html code, then process it with bs4.BeautifulSoup.prettify() Custom formatters can be created to alter the result of prettify()

Thanks @Gribouillis, actually I generated the most of my pages with Jinja..
I've never used BeautifulSoup so If I understand correctly I could create the HTML Tag / structure trough
BeautifulSoup ? correct ? IS it better (do we have the hand of all the option the provide the HTML tag ?

Thanks.
[Image: NfRQr9R.jpg]
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Using one child class method in another child class garynewport 5 1,609 Jan-11-2023, 06:07 PM
Last Post: garynewport
  Find if chain of characters or number Frankduc 4 1,806 Feb-11-2022, 01:55 PM
Last Post: Frankduc
  How to access parent object attribute Pavel_47 2 8,774 Nov-19-2021, 09:36 PM
Last Post: deanhystad
  Can we access instance variable of parent class in child class using inheritance akdube 3 14,005 Nov-13-2020, 03:43 AM
Last Post: SalsaBeanDip
  How to Locate an Attribute's Parent Object? calvinsomething 5 3,008 Nov-13-2020, 01:52 AM
Last Post: calvinsomething
  Python3 binary tree not replacing parent nodes with child nodes Aspect11 0 1,780 Sep-23-2020, 02:22 PM
Last Post: Aspect11
  Getter/Setter : get parent attribute, but no Getter/Setter in parent nboweb 2 2,995 May-11-2020, 07:22 PM
Last Post: nboweb
  updating certain values in dict. with relation to their keys malevy 17 5,346 Nov-27-2019, 02:37 PM
Last Post: buran
  XML Parsing Child karthi_python 1 1,894 May-16-2019, 01:37 PM
Last Post: karthi_python
  logging: child module unable to get parent config jerryxiao 3 3,383 Apr-09-2019, 04:17 AM
Last Post: jerryxiao

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020