【问题标题】:Best way to format a nested Python dictionary to be rendered in a jinja2 templates格式化嵌套 Python 字典以在 jinja2 模板中呈现的最佳方法
【发布时间】:2016-04-17 18:41:06
【问题描述】:

您好,我有一个这样的 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 ;

【问题讨论】:

    标签: python dictionary jinja2


    【解决方案1】:

    你应该写一个自定义过滤器...

    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 的描述进行设置,或者,举个完整的例子,here。然后,你可以这样做:

    {{ data|format_dict }}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-27
      • 2016-07-18
      • 2015-07-03
      • 2010-10-12
      • 1970-01-01
      • 2023-01-09
      • 2013-05-15
      相关资源
      最近更新 更多