嗨,我有一个Python嵌套字典,如下所示:
fv_solution = {
'relaxationFactors':
{
'fields':
{
'\"(p|pa)\"': 0.3,
'alpha': 0.1,
},
'equations':
{
'\"(U|Ua)\"': 0.7,
'\"(k|epsilon)\"': 0.7,
}
},
'relaxationFactors2':
{
'fields':
{
'\"(p|pa)\"': 0.3,
'alpha': 0.1,
},
'equations':
{
'\"(U|Ua)\"': 0.7,
'\"(k|epsilon)\"': 0.7,
}
}
}
我想这样渲染到文件:
relaxationFactors
{
fields
{
"(p|pa)" 0.3;
alpha 0.1;
}
equations
{
"(U|Ua)" 0.7;
"(k|epsilon)" 0.7;
}
}
relaxationFactors2
{
fields
{
"(p|pa)" 0.3;
alpha 0.1;
}
equations
{
"(U|Ua)" 0.7;
"(k|epsilon)" 0.7;
}
}
我最好的方法是使用替换过滤器,但除此之外,它不是一个优雅的解决方案,其结果也不理想
我的过滤器
{{ data|replace(':',' ')|replace('{','\n{\n')|replace('}','\n}\n')|replace(',',';\n')|replace('\'','') }}
结果
{ # <- not needed
relaxationFactors2
{
fields
{
alpha 0.1;
"(p|pa)" 0.3 # <- missing ;
}
; # <- aditional ;
equations
{
"(U|Ua)" 0.7;
"(k|epsilon)" 0.7 # <- missing ;
}
} # <- not needed
; # <- aditional ;
relaxationFactors
{
fields
{
alpha 0.1;
"(p|pa)" 0.3 # <- missing ;
}
; # <- aditional ;
equations
{
"(U|Ua)" 0.7;
"(k|epsilon)" 0.7 # <- missing ;
}
}
} # <- not needed ;
您应该编写一个自定义过滤器...
def format_dict(d, indent=0):
output = []
for k, v in d.iteritems():
if isinstance(v, dict):
output.append(indent*' ' + str(k))
output.append(indent*' ' + '{')
output.append(format_dict(v, indent+4))
output.append(indent*' ' + '}')
else:
output.append(indent*' ' + str(k).ljust(16) + str(v) + ';')
return '\n'.join(output)
...并设置它描述正式在这里,或者用一个完整的例子,在这里。然后,您可以执行以下操作:
{{ data|format_dict }}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句