I have a nested dictionary,
d={
"A":1,
"depth":0,
"chain":[
{
"A1":0.7,
"depth":1,
"chain":[
{
"A11":0.3,
"depth":2,
"key2":{"direct":{},"cumulative":{"B":0.3}},
"chain":[]
},
{
"A12":0.4,
"depth":2,
"chain":[
{
"A121":0.4,
"depth":3,
"key2":{"direct": {}, "cumulative":{"C":0.2, "D": 0.2}},
"chain": []
}]}]},
{
"A2":0.3,
"depth":1,
"chain":[
{
"A11":0.3,
"depth":2,
"key2":{"direct":{}, "cumulative":{"D":0.3}},
"chain":[]
}]}]}
I want to return a list that the first key is repeated by x times. x is the number of elements under "chain". In this case, it would return:
["A", "A", "A1", "A1", "A2", "A12"]
I have tried the following
def from_nodes(d):
from_n=[list(d.keys())[0]]*len(d["chain"])
for x in d["chain"]:
if x is not None:
from_n.extend(from_nodes(x))
return from_n
and got the error
TypeError Traceback (most recent call last)
<ipython-input-196-6233463c604b>in <module>()
----> 1 from_nodes(test2)
<ipython-input-194-5b7ca4b6db75>in from_nodes(d)
3 for x in d["chain"]:
4 if x is not None:
----> 5 from_n.extend(from_nodes(x))
6 return from_n
<ipython-input-194-5b7ca4b6db75> in from_nodes(d)
3 for x in d["chain"]:
4 if x is not None:
----> 5 from_n.extend(from_nodes(x))
6 return from_n