Home > Enterprise >  Trying to create family tree from dictinoary
Trying to create family tree from dictinoary

Time:05-01

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":[]}]}]}]}

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?

CodePudding user response:

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": []}]},
            ]
        }
    ]
}
  • Related