I have a dictionary that I would like to parse recursively and build a structure of Dash components (knowledge of the components is unnecessary as long as you know that .children
is a list). I am able to figure out how to do it a couple levels down but this will get tedious as the dictionary becomes large. How can I handle this recursively (or can I)?
d = {'1': {'1.1': {'1.1.1': {}}, '1.2': {'1.2.1': {}}},
'2': {'2.1': {'2.1.1': {}}, '2.2': {'2.2.2': {}}}}
C = dbc.Accordion([])
for i in d.keys():
B = dbc.Accordion([])
for j in d[i].keys():
A = dbc.Accordion([])
for k in d[i][j].keys():
A.children.append(dbc.AccordionItem([], title=k))
B.children.append(dbc.AccordionItem(A, title=j))
C.children.append(dbc.AccordionItem(B, title=i))
print(C)
(There might be a better title for my question)
EDIT: The accordion objects allow me to create a nested menu:
When I print(C)
, this is the output I need:
Accordion(children=[AccordionItem(children=Accordion(children=[AccordionItem(children=Accordion(children=[AccordionItem(children=[], title='1.1.1')]), title='1.1'), AccordionItem(children=Accordion(children=[AccordionItem(children=[], title='1.2.1')]), title='1.2')]), title='1'), AccordionItem(children=Accordion(children=[AccordionItem(children=Accordion(children=[AccordionItem(children=[], title='2.1.1')]), title='2.1'), AccordionItem(children=Accordion(children=[AccordionItem(children=[], title='2.2.2')]), title='2.2')]), title='2')])
EDIT 2:
Here is some code that allows demonstration of what I need without needing the dbc
module (this is important because as I recurse through the dictionary I need to be able to use these different datatypes - that behave like lists):
class Accordion:
def __init__(self, list_):
self.list_ = list_
def __str__(self):
return f'Accordion({self.list_})'
def append_(self, item):
return self.list_.append(item)
class AccordionItem:
def __init__(self, list_, title):
self.list_ = list_
self.title = title
def __repr__(self):
return f"AccordionItem('{self.list_}', title='{self.title}')"
d = {'1': {'1.1': {'1.1.1': {}}, '1.2': {'1.2.1': {}}},
'2': {'2.1': {'2.1.1': {}}, '2.2': {'2.2.2': {}}}}
C = Accordion([])
for i in d.keys():
B = Accordion([])
for j in d[i].keys():
A = Accordion([])
for k in d[i][j].keys():
A.append_(AccordionItem([], k))
B.append_(AccordionItem(A, j))
C.append_(AccordionItem(B, i))
print(C)