Skip to content Skip to sidebar Skip to footer

How To Create A Bootstrap Accordion From A Nested Dictionary In Python?

I have a nested dictionary like this one: d = {1: {4: {6: {}, 7: {}, 8: {}}, 5: {}}, 2: {}, 3: {}} Which can be visualized as: 1 4 6 7 8 5 2 3 My goa

Solution 1:

I was able to reach my result on my real problem. Here is the code:

defpretty(d, indent=0, indent_previous_layer=-1, counter=0):
    html_code = ''
    indent_privious_item = indent_previous_layer
    for key, value in d.items():             
            
        if indent > indent_privious_item and counter!=0:
            html_code += """
            <div id="collapse-{}" class="collapse" data-parent="#accordion-{}" aria-labelledby="heading-{}">
            <div class="card-body">
                <div id="accordion-{}">
            """.format(counter, indent-1, counter, indent)
        elif indent == indent_privious_item:
            html_code += """
            </div>
            """if indent==0:
                html_code += """
                <!--End of Card-->
                """elif indent < indent_privious_item:
            if indent==0:
                html_code += """
                                </div>
                """
                html_code += """
                            </div>
                        </div>
                    </div>
                </div>
                """*(indent_privious_item-indent)
                html_code += """
                <!--End of Card-->
                """else:
                html_code += """
                                </div>
                """
                html_code += """
                            </div>
                        </div>
                    </div>
                </div>
                """*(indent_privious_item-indent)

        html_code +="""
        <div class="card">
        <div class="card-header" id="heading-{}">
            <h5 class="mb-0">
                <a role="button" data-toggle="collapse" href="#collapse-{}" aria-expanded="true" aria-controls="collapse-{}">
                 Depth Level {}
                </a>
            </h5>
        </div>
            <div class="card-body pb-0">
                <!--h5 class="card-title"></h5-->
                <p class="card-text">{}</p>
                    <ul class="list-group">""".format(counter+1, counter+1, counter+1, indent, "Some text")

        html_code += """
                    </ul>
            </div>
    
            """ifisinstance(value, dict):
            code, indent_privious_item, counter = pretty(value, indent+1, indent, counter+1)
            html_code += code
        else:
            print('\t' * (indent+1) + str(value))
        
    return html_code, indent_privious_item, counter

Note: the indentation may be off. Feel free to fix it

Post a Comment for "How To Create A Bootstrap Accordion From A Nested Dictionary In Python?"