Answer the question
In order to leave comments, you need to log in
How to display all values from a multidimensional dictionary?
I have a dictionary that can change in size and the number of other
dictionaries nested in it can be different.
arr = {
'1':{
'id': 1,
'name': 'test_1',
'child': {
'2':{
'id': 1,
'name': 'test_2',
'child': {
'3':{
'id': 3,
'name': 'test_3',
'child': {}
}
}
}
}
},
'4':{
'id': 4,
'name': 'test_4',
'child': {}
}
}
<ul>
<ul>
<li>
test_1
</li>
<ul>
<li>
test_2
</li>
<ul>
<li>
test_3
</li>
</ul>
</ul>
</ul>
<ul>
<li>
test_4
</li>
</ul>
</ul>
html = "<ul>"
for x in arr:
html = html + "<ul>"
val_1 = arr[x]['name']
html = html + "<li>" + val_1 + "</li>"
for y in arr[x]['child'] :
html = html + "<ul>"
val_2 = arr[x]['child'][y]['name']
html = html + "<li>" + val_2 + "</li>"
for b in arr[x]['child'][y]['child'] :
html = html + "<ul>"
val_3 = arr[x]['child'][y]['child'][b]['name']
html = html + "<li>" + val_3 + "</li>"
html = html + "</ul>"
html = html + "</ul>"
html = html + "</ul>"
html = html + "</ul>"
print(html)
<ul>
<li>
test_1
</li>
<li>
test_2
</li>
<li>
test_3
</li>
<li>
test_4
</li>
</ul>
Answer the question
In order to leave comments, you need to log in
In the dictionary you provided at the first level, the same keys (id, name, child) are repeated 2 times and overwritten.
But in the general case, I would write a recursive function for such a task.
For example:
def print_recursive(data, offset=''):
def is_leaf(element):
return not bool(element.get('child'))
if is_leaf(data):
print(offset + '<li>')
print(offset + data.get('name'))
print(offset + '</li>')
return
print(offset + '<ul>')
print_recursive(data['child'], offset=offset + ' ')
print(offset + '</ul>')
arr = {} # тут ваш словарь
print_recursive(arr)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question