我在python中嵌套了字典:
result = {'Physics': {'Mechanics': {'Kinematics ': {}, 'Dynamics': {}}}, 'Math': {'Algebra': {'Polynomials': {'sum of polynomials': {}}}}}
我需要在flask/jinja中打印此数据。我想要得到一个树或者一个嵌套列表。结果应该是:
<ul class="list">
<li class="title">
<a href="/">"Physics"</a>
</li>
<ul class="list2">
<li class="title2">
<a href="/">"Mechanics"</a>
</li>
<ul class="list3">
<li class="title3">
<a href="/">"Kinematics "</a>
</li>
<li class="title3">
<a href="/">'Dynamics'</a>
</li>
</ul>
</ul>
</ul>
<ul class="list">
<li class="title">
<a href="/">'Math'</a>
</li>
<ul class="list2">
<li class="title2">
<a href="/">'Algebra'</a>
</li>
<ul class="list3">
<li class="title3">
<a href="/">'Polynomials'</a>
</li>
<ul class="list4">
<li class="title4">
<a href="/">'sum of polynomials'</a>
</li>
</ul>
</ul>
</ul>
</ul>
我该如何解决我的问题?
您可以使用递归创建字典的HTML标记,然后将结果字符串传递给模板:
def to_html(d, c = 1):
if not all(d.values()):
return f'<ul class="list{"" if c == 1 else c}">'+'n'.join(f'<li class="title{"" if c == 1 else c}"><a href="/">{a}</a></li>{"" if not b else to_html(b, c+1)}' for a, b in d.items())+'</ul>'
return 'n'.join(f'<li class="title{"" if c == 1 else c}"><a href="/">{a}</a></li>' if not b else
f"""
<ul class="list{"" if c == 1 else c}">
<li class="title{"" if c == 1 else c}"><a href="/">{a}</a></li>
{to_html(b, c+1)}
</ul>
"""
for a, b in d.items())
d = {'Physics': {'Mechanics': {'Kinematics ': {}, 'Dynamics': {}}}, 'Math': {'Algebra': {'Polynomials': {'sum of polynomials': {}}}}}
print(to_html(d))
输出:
<ul class="list">
<li class="title">
<a href="/">
Physics
</a>
</li>
<ul class="list2">
<li class="title2">
<a href="/">
Mechanics
</a>
</li>
<ul class="list3">
<li class="title3">
<a href="/">
Kinematics
</a>
</li>
<li class="title3">
<a href="/">
Dynamics
</a>
</li>
</ul>
</ul>
</ul>
<ul class="list">
<li class="title">
<a href="/">
Math
</a>
</li>
<ul class="list2">
<li class="title2">
<a href="/">
Algebra
</a>
</li>
<ul class="list3">
<li class="title3">
<a href="/">
Polynomials
</a>
</li>
<ul class="list4">
<li class="title4">
<a href="/">
sum of polynomials
</a>
</li>
</ul>
</ul>
</ul>
</ul>
然后,在flask
中:
@app.route('/hierarchy', methods=['GET'])
def hierarchy():
d = {'Physics': {'Mechanics': {'Kinematics ': {}, 'Dynamics': {}}}, 'Math': {'Algebra': {'Polynomials': {'sum of polynomials': {}}}}}
return flask.render_template('show_hierarchy.html', hierarchy=to_html(d))
show_hierarchy.html
:
<h1>Hierarchy</h1>
{{hierarchy}}