试图从字典创建家谱
Trying to create family tree from dictinoary
我正在尝试从我的词典中创建“child,parent”词典。我怎样才能做到这一点?
这是我的命令:
{"Sıdıka":[{"Aziz":[{"Ahmet":[{"Kuzey":[]}],"Öznur":[{"Elif":[]},{"Yiğit":[]}],"İlknur":[{"Nurullah":[]},{"Büşra":[]}],"İlker":[{"Melih":[]}]}]}]}
从左到右的祖先正在成长。 Sıdıka 是 grand grand grand grand grand mother,aziz 是她的儿子。而“ahmet、öznur、ilknur、ilker”是“aziz”children 等等。
我想要这样的字典:
{'Sıdıka':[{'Aziz':[{'Ahmet':[{'Kuzey':[]}],'Öznur':[{'Elif':[]},{'Yiğit':[]}],'İlknur':[{'Nurullah':[]},{'Büşra':[]}],{'İlker':[{'Melih':[]}]}]
我想我需要一个非常好的算法。有帮助吗?
您可以对任务使用递归:
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"))
打印:
{
"Sıdıka": [
{
"Aziz": [
{"Ahmet": [{"Kuzey": []}]},
{"Öznur": [{"Elif": []}, {"Yiğit": []}]},
{"İlknur": [{"Nurullah": []}, {"Büşra": []}]},
{"İlker": [{"Melih": []}]},
]
}
]
}
我正在尝试从我的词典中创建“child,parent”词典。我怎样才能做到这一点?
这是我的命令:
{"Sıdıka":[{"Aziz":[{"Ahmet":[{"Kuzey":[]}],"Öznur":[{"Elif":[]},{"Yiğit":[]}],"İlknur":[{"Nurullah":[]},{"Büşra":[]}],"İlker":[{"Melih":[]}]}]}]}
从左到右的祖先正在成长。 Sıdıka 是 grand grand grand grand grand mother,aziz 是她的儿子。而“ahmet、öznur、ilknur、ilker”是“aziz”children 等等。 我想要这样的字典:
{'Sıdıka':[{'Aziz':[{'Ahmet':[{'Kuzey':[]}],'Öznur':[{'Elif':[]},{'Yiğit':[]}],'İlknur':[{'Nurullah':[]},{'Büşra':[]}],{'İlker':[{'Melih':[]}]}]
我想我需要一个非常好的算法。有帮助吗?
您可以对任务使用递归:
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"))
打印:
{
"Sıdıka": [
{
"Aziz": [
{"Ahmet": [{"Kuzey": []}]},
{"Öznur": [{"Elif": []}, {"Yiğit": []}]},
{"İlknur": [{"Nurullah": []}, {"Büşra": []}]},
{"İlker": [{"Melih": []}]},
]
}
]
}