格式化要在 jinja2 模板中呈现的嵌套 Python 字典的最佳方法

Best way to format a nested Python dictionary to be rendered in a jinja2 templates

您好,我有一个 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)

... 并按照 officially here or, with a full example, here 所述进行设置。然后,你可以这样做:

{{ data|format_dict }}