I've been struggling for a while trying to figure it out to put some hierarchical values in a flat table into a specific dictionary format. The main issue is that I couldn't figure it out how to nest each category inside their corresponding key.
I have this table (as a pandas DataFrame) with the column stating the hierarchy as a number: The table has three columns:
Level Name Description
0 Main ...
1 Sub main ...
2 Sub sub main ...
1 Sub main ...
2 Sub sub main ...
3 Sub sub sub main ...
0 Main_2 ...
. . .
And the expected output should be something like this:
{
"nodes": [
{
"name": "main",
"description": "",
"owners":{
"users":["Sandra"]
},
"terms":[{
"name":"",
"description":""
}]
},
{
"nodes": [
{
"name": "sub_main",
"description": "",
"owners":{
"users":[""]
},
"terms":[{
"name":"",
"description":"",
"inherits":[""]
}]
},
{
"nodes": [
{
"name": "sub_sub_main",
"description": "",
"owners":{
"users":[""]
},
"terms":[{
"name":"",
"description":"",
"inherits":[""]
}]
},
]
}
]
}
]
}
I have a large table with multiple hierarchical levels. Sometimes it's just 2 or 3 levels and in others, more. But, all of them are in order.
The other thing is that in inherits
section, there must appear the parents above them.
I'm trying to build a recursive function but I have failed so far. I have checked these other similar questions:
- Build nested/hierarchical dictionary from irregular flat dictionary
- Access nested dictionary items via a list of keys?
Does anyone know any questions similar to this approach? Or if any of you have faced a similar problem?
Thank you all in advance!