我需要创建一个嵌套的 dict 结构,其中子级的数量可以在每个级别有所不同。
将“大小”元素附加到旭日形图的最后一个 json 子元素 这个问题涵盖了树的创建,除了我需要从最后一列中选取大小。
鉴于我的标签在级别之间重复,并且每个级别都可以具有与终端级别相同的标签“abc”,以及下一级的父级 - 我在这里稍微修改了代码(以避免在子分支中重复)。但是,我无法指定存储在最后一列中的大小,并且应该替换每个叶端的 1。我知道我需要将行中的值传递给递归循环 build_leaf,但似乎无法弄清楚如何。
import csv
from collections import defaultdict
import json
def ctree():
return defaultdict(ctree)
def build_leaf(name, leaf):
if len(name)==0:
res={"name":"last node"}
res['size']=1
else:
res = {"name": name}
# add children node if the leaf actually has any children
if len(leaf.keys())>0:
res["children"] = [build_leaf(k, v) for k, v in leaf.items()]
else:
res['size'] = 1
return res
def main():
tree = ctree()
# NOTE: you need to have test.csv file as neighbor to this file
with open('./inpfile.csv') as csvfile:
reader = csv.reader(csvfile)
header = next(reader) # read the header row
i=0
for row in reader:
# usage of python magic to construct dynamic tree structure and
# basically grouping csv values under their parents
leaf = tree[row[0]]
size=row[-1]
for value in row[1:-1]:
leaf = leaf[value]
# building a custom tree structure
res = []
for name, leaf in tree.items():
res.append(build_leaf(name, leaf))
# printing results into the terminal
print(json.dumps(res, indent=2))
with open('paths.json', 'w') as fp:
json.dump(res, fp)
main()
所提及数据的最终输出应类似于:
[
{
"name": "A1",
"children": [
{
"name": "A2",
"children": [
{
"name": "A1",
"children": [
{
"name": "A2",
"children": [
{
"name": "A3",
"size": 80
}
]
}
]
},
翻过高山走不出你
相关分类