Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trying to create family tree from dictinoary

I am trying to create "child,parent" dictionary from my dictionary. How can i achieve that?

Here is my dict:

{"Sıdıka":[{"Aziz":[{"Ahmet":[{"Kuzey":[]}],"Öznur":[{"Elif":[]},{"Yiğit":[]}],"İlknur":[{"Nurullah":[]},{"Büşra":[]}],"İlker":[{"Melih":[]}]}]}]}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Left to right ancestors are growing. Sıdıka is grand grand grand grand mother, aziz is her son. And "ahmet, öznur,ilknur,ilker" are "aziz"s children etc. etc.
I want a dictionary something like this:

{'Sıdıka':[{'Aziz':[{'Ahmet':[{'Kuzey':[]}],'Öznur':[{'Elif':[]},{'Yiğit':[]}],'İlknur':[{'Nurullah':[]},{'Büşra':[]}],{'İlker':[{'Melih':[]}]}]

I think i need a very good algorithm for this. Any help?

>Solution :

You can use recursion for the task:

d = {
    "Sıdıka": ["Aziz"],
    "Aziz": ["Ahmet", "Öznur", "İlknur", "İlker"],
    "Ahmet": ["Kuzey"],
    "Öznur": ["Elif", "Yiğit"],
    "İlknur": ["Nurullah", "Büşra"],
    "İlker": ["Melih"],
}


def get_tree(root):
    return {root: [get_tree(v) for v in d.get(root, [])]}


print(get_tree("Sıdıka"))

Prints:

{
    "Sıdıka": [
        {
            "Aziz": [
                {"Ahmet": [{"Kuzey": []}]},
                {"Öznur": [{"Elif": []}, {"Yiğit": []}]},
                {"İlknur": [{"Nurullah": []}, {"Büşra": []}]},
                {"İlker": [{"Melih": []}]},
            ]
        }
    ]
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading