Python Forum

Full Version: Chain object that have parent child relation..
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
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
Would that not look like this?
names = {
    "John": {
        "David": {
            "Grunt": None
        },
        "Jade": None
    }
}
@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 ?
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.
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': {}}}
>>> 
@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>
(Dec-11-2023, 10:01 AM)SpongeB0B Wrote: [ -> ]I would like to print a hierarchy
What have you tried? Post your code!
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..
(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()
(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.
Pages: 1 2