【问题标题】:How can you create dictionaries of keys mapping to lists, with each element in the lists pointing to other lists, in Python?如何在 Python 中创建映射到列表的键的字典,列表中的每个元素都指向其他列表?
【发布时间】:2018-12-12 21:38:22
【问题描述】:

例如:

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 个),每个子级都可以指向其多个子级。还有其他方法吗?

【问题讨论】:

  • 是的,您只需要一个字典而不是针对每个键存储的列表。但是你打算走多远?很快我认为它会变得笨拙
  • d["Child3"].append("GrandChild1")如果你只是想建立映射
  • 假设它最多有 5 个深度级别
  • 但是 d["Child3"].append("GrandChild1") 没有建立映射,因为它没有显示“Parent”到“Child3”到“GrandChild1”的层次结构(其中看起来像 d["Parent"]["Child3"].append("GrandChild1"),但这是不正确的。
  • 它基本上是一个树实现,其中一个节点指向它的子节点,但我不知道如何用字典和列表来实现它。

标签: python dictionary data-structures tree


【解决方案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'])

【讨论】:

  • 我正在尝试用它构建一个树结构,我可以在它上面进行深度优先遍历。给定一个 JSON 列表:locations = [ {"id": 1, "name": "San Francisco Bay Area", "parent_id": None}, {"id": 2, "name": "San Jose", " parent_id”:3},{“id”:3,“name”:“南湾”,“parent_id”:1},{“id”:4,“name”:“旧金山”,“parent_id”:1 }, {"id": 5, "name": "Manhattan", "parent_id": 6}, {"id": 6, "name": "New York", "parent_id": None} ] 我想能够打印每个父母及其子女:纽约-曼哈顿旧金山湾区-旧金山-南湾-圣何塞
  • 在 Python 中有没有比字典映射到列表更简洁的方法?
  • 不确定您的代码如何解决它。如果给定一个 JSON 列表,其中每个元素都告诉您其父 ID 是什么(顶级父级将是 None),我希望能够从中创建一个树结构,其中每个顶级父级映射到其子级及其每个儿童(最大深度为 5)。使用您的解决方案,尚不清楚我将如何遍历 JSON 列表并创建每个映射。例如,如果我正在遍历 JSON 列表并看到“GrandChild1”是给定其 parent_id 的“Child3”的孩子,那么我怎么知道“Child3”是“Parent”的孩子并分配它的方式你做了吗?
  • 是的,最多可以有 5 个级别。但基本上目标是获取该 JSON 列表并输出每个父级及其下的子级,并在每个子级别添加一个“-”(连字符)。
  • 谢谢@Jayjayyy,这真的很有帮助。您将如何跟踪每个级别?例如,我想按字母顺序对每个级别进行排序,并为每个级别添加一个连字符(级别 1 在子级之前会有“-”,级别 2 会在每个子级之前有“--”,等等
【解决方案2】:

对如何在 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))

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-09
    • 1970-01-01
    • 2016-09-13
    • 1970-01-01
    • 2018-07-08
    相关资源
    最近更新 更多