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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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": []}]},
]
}
]
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0