Nested <ul><li> navigation menu using a recursive Python function

Posted by Alex on Stack Overflow See other posts from Stack Overflow or by Alex
Published on 2010-05-22T16:15:48Z Indexed on 2010/05/22 16:20 UTC
Read the original article Hit count: 203

Filed under:
|
|
|

Hi. I want to render this data structure as an unordered list.

menu = [
         [1, 0],
           [2, 1],
           [3, 1],
             [4, 3],
          [5, 3],
           [6, 5],
           [7,1]
        ]

[n][0] is the key
[n][1] references the parent key

The desired output is:

<ul>
<li>Node 1</li>

  <ul>
  <li>Node 2</li>
  <li>Node 3</li>

    <ul>
    <li>Node 4</li>
    <li>Node 5</li>

      <ul>
      <li>Node 6</li>
      </ul>

    </ul>

   <li>Node 7</li>
   </ul>

</ul>

I could probably do this without recursion but that would be no fun. Unfortunately, I am having problems putting it all together. I don't have much experience with recursion and this is proving to be very difficult for me to build and debug.

What is the most efficient way to solve this problem in Python?

Thanks!

© Stack Overflow or respective owner

Related posts about python

Related posts about recursion