如何在Python中创建映射到列表的键的字典,使列表中的每个元素指向其他列表?

时间:2018-12-12 21:38:22

标签: python dictionary data-structures tree

例如:

d = dict()

#Map "Parent" to a list of "children" values
d["Parent"] = []
d["Parent"].append("Child1")
d["Parent"].append("Child2")
d["Parent"].append("Child3")

#I know the following is wrong, but I want each list that "Parent" maps to, also to map to a list- how would I do this?
d["Parent"]["Child3"] = []
d["Parent"]["Child3"].append("GrandChild1")

这基本上看起来像是一棵树(不是二叉树),其中有一个顶级父级,指向其子级(可能超过2个),每个子级都可以指向其多个子级。还有其他方法吗?

2 个答案:

答案 0 :(得分:1)

我认为,您正在尝试执行以下操作:

d = {}

d["Parent"] = {}

d["Parent"]["Child1"] = {}
d["Parent"]["Child2"] = {}
d["Parent"]["Child3"] = {}

d["Parent"]["Child3"]["GrandChild1"] = {}
d["Parent"]["Child3"]["GrandChild2"] = {}

但是,您要去哪里?这可能不是使用Python做到这一点的最佳方法。 :-)如果可以使当前代码正常工作,则可以在之后将其发布到https://codereview.stackexchange.com/。您将获得有关如何改进代码的宝贵反馈。


顺便说一句,然后您可以使用dict.keys查看“树”的“分支”:

print(d.keys())
print(d["Parent"].keys())
print(d["Parent"]["Child3"].keys())

哪些印刷品

dict_keys(['Parent'])
dict_keys(['Child3', 'Child2', 'Child1'])
dict_keys(['GrandChild2', 'GrandChild1'])

答案 1 :(得分:0)

对如何在python中做树感兴趣,我到处搜索并在GitHub上找到了一些示例代码,以获取One-line Tree in Python

defaultdict创建树:

from collections import defaultdict
def tree(): return defaultdict(tree)

建立您的树形结构:

t = tree()
t['San Francisco Bay Area']['San Francisco']
t['San Francisco Bay Area']['South Bay']['San Jose']
t['New York']['Manhattan']

并打印出来;

import json
print(json.dumps(t))
  

{“纽约”:{“曼哈顿”:{}},“旧金山湾区”:{“旧金山”:{},“南湾”:{“圣何塞”:{}}}}

关于迭代的更多信息,以及在注释中的更有用的代码和建议,有关如何从json加载它并漂亮地打印结构。