嵌套字典中的父级和子级列表

时间:2016-07-13 12:17:12

标签: python dictionary nested

我有一个列表,我想转换成嵌套字典。列表的第一个元素是父元素,第二个元素是子元素。我是否可以递归执行此操作而无需继续为每个级别创建帮助程序列表?我觉得愚蠢不明白这一点。

relations = [["basket", "money"],
             ["basket", "fruits"],
             ["fruits", "orange"],
             ["fruits", "apple"],
             ["basket", "vegetables"],
             ["vegetables", "bean"],
             ["vegetables", "tomato"],
             ["tomato", "red tomato"],
             ["tomato", "green tomato"],
             ["vegetables", "pepper"],
             ["sweets", "candy"]]


result = {}
running_list = []

for parent, child in relations:
    if parent == "basket":
        result[child] = {}
        running_list.append(child)

for parent, child in relations:
    if parent in running_list:
        result[parent] = {child : {}}

print result

1 个答案:

答案 0 :(得分:2)

只需创建一个将名称映射到相应字典的字典:

items = {}
for parent, child in relations:
    parent_dict = items.setdefault(parent, {})
    child_dict = items.setdefault(child, {})
    if child not in parent_dict:
        parent_dict[child] = child_dict

result = items['basket']  # basket is the top-level item

这会产生:

>>> items = {}
>>> for parent, child in relations:
...     parent_dict = items.setdefault(parent, {})
...     child_dict = items.setdefault(child, {})
...     if child not in parent_dict:
...         parent_dict[child] = child_dict
...
>>> items['basket']
{'money': {}, 'vegetables': {'tomato': {'green tomato': {}, 'red tomato': {}}, 'bean': {}, 'pepper': {}}, 'fruits': {'orange': {}, 'apple': {}}}
>>> from pprint import pprint
>>> pprint(items['basket'])
{'fruits': {'apple': {}, 'orange': {}},
 'money': {},
 'vegetables': {'bean': {},
                'pepper': {},
                'tomato': {'green tomato': {}, 'red tomato': {}}}}