F
F
fantom_ask2020-05-11 15:20:46
Python
fantom_ask, 2020-05-11 15:20:46

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': {}
}
}


But I don't understand how to create a loop that will display all values ​​in this format

<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>

write constantly
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)

Doesn't work for me
How do they solve such problems in python?

As an analogy, I can give get_comments() from wordpress.

I can't figure out how she manages to nest a comment within each other, regardless of the amount of nesting. in one cycle

The only thing I can do is
<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

2 answer(s)
P
Pavel Botsman, 2020-05-11
@fantom_ask

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)

0
0ralo, 2020-05-11
@0ralo

Perhaps the pprint library will help

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question