我在csv中以
的形式获得数据"category1", 2010, "deatil1"
"category1", 2010, "deatil2"
"category1", 2011, "deatil3"
"category2", 2011, "deatil4"
我需要以
的形式将其映射到json {
"name": "Data",
"children": [{
"name": "category1",
"children": [{
"name": "2010",
"children": [
{"name": "deatil1"},
{"name": "detail2"}
],
"name": "2011",
"children": [
{"name": "detail3"}
]
}, {
}]
},
{
"name": "category2",
"children": [{
"name": "2011",
"children": [{
"name": "detail4"
}]
}
]
}
]
}
基本上我需要收集每个唯一类别和年份对的所有细节并列出
我试图使用嵌套的dict结构,但输出不正确。
我创建了一个自定义dict类来处理字典嵌套的嵌套。以下代码收集正确结构中的数据,但我不确定如何以正确的格式继续输出它。任何帮助将不胜感激。
class Vividict(dict):
def __missing__(self, key):
value = self[key] = type(self)()
return value
dict = Vividict()
for row in ws.iter_rows(row_offset=1):
sector = row[0].value
year = row[2].value
detail = row[1].value
dict[sector][year][detail]
print json.dumps(dict).encode('utf8')
答案 0 :(得分:4)
从dict
结构开始,这是建立新数据结构的问题。我在这里使用的主要是列表推导,其中创建了import json
rows = [
("category1", 2010, "deatil1"),
("category1", 2010, "deatil2"),
("category1", 2011, "deatil3"),
("category2", 2011, "deatil4")]
class Vividict(dict):
def __missing__(self, key):
value = self[key] = type(self)()
return value
dict = Vividict()
for row in rows:
sector = row[0]
year = row[1]
detail = row[2]
dict[sector][year][detail]
# This is the new data structure, derived from the existing 'dict'
d = {'name': 'Data',
'children': [
{'name': k1, # sector
'children': [
{'name': k2, # year
'children': [
{
'name': k3 # deatil
} for k3 in v2.keys()]
} for k2, v2 in v1.iteritems()]
} for k1, v1 in dict.iteritems()]
}
print json.dumps(d).encode('utf8')
:
<h1>
在此处查看此行动:https://eval.in/662805