[英]List of parent and child into nested dictionary
我有一个列表,希望将其转换为嵌套字典。 列表的第一个元素是父元素,第二个元素是子元素。 我可以递归地执行此操作,而不必继续为每个级别创建帮助者列表吗? 我不明白这一点真是愚蠢。
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
只需创建一个将名称映射到相应字典的字典即可:
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': {}}}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.