私が抱えている Python の問題について助けが必要です。親/子辞書を作成したいMySQLデータベースからのデータがあります。
私が取得しているデータには、名前とサイズの 2 つの値が含まれています。
{
"name": " ",
"children": [
{
"name": "HSC",
"size": 0.2,
"children": [
{
"name": "MPP",
"size": 15,
"children": [
{
"name": "CMP",
"size": 8,
"children": [
{
"name": "MEP",
"size": 6
},
{
"name": "GMP",
"size": 10,
"children": [
{
"name": "early PM",
"size": 2
}
]
}
]
}
]
}
]
}
]
}
私はいくつかのコードを書いています:
cur.execute('SELECT DISTINCT gene_data.gene_name, gene_data.mean FROM genes INNER JOIN gene_data ON genes.id = gene_data.g_id WHERE genes.name = %s AND genes.type = %s AND gene_data.probe_name = %s', (gene, types, probe))
rows = cur.fetchall()
cmap = {}
for row in rows:
entry = {'name': row[0], 'size': row[1], 'children':[]}
cmap[row[0]] = entry
for index, row in enumerate(rows):
item = cmap[row[0]]
if((index+2)>len(rows)):
parent = cmap.get( row[0], None )
parent["children"].append(item.copy())
if parent:
parent["children"].append(item.copy)
hrcy = parent["children"]
print hrcy
else:
next = rows[index+1]
nextItem = cmap[next[0]]
parent = cmap.get( row[0], None )
#parent["children"].append(nextItem.copy())
if parent:
parent["children"].append(nextItem.copy())
このコードを実行すると、1 行しか取得できません。以前の子要素にすべての行を追加する必要があります。