【问题标题】:displaying a mapping of all keys in a nested dictionary in Jinja2在 Jinja2 的嵌套字典中显示所有键的映射
【发布时间】:2022-06-16 12:48:21
【问题描述】:

我还是 Jinja 的新手,所以如果我的问题措辞不当,请提前道歉。我正在尝试显示访问嵌套字典中特定值所需的键的映射。我希望输出显示字典的键,箭头指向下一个嵌套键,依此类推key1 --> key2 --> key3 --> value

我正在使用的字典如下所示:

x = {
      "food": {},
      "dessert": {},
      "vehicles": {
        "trucks": {},
        "cars": {
          "brands": {
            "german brands": ["Audi", "BMW"],
            "american brands": ["Dodge", "Chevy"]
          },
          "seats": {
            "types": ["leather"]
          }
        },
        "color": ["black", "white"]
      },
      "electronics": {"laptops": {}}
  }

我希望输出以如下格式显示结果:

food --> {}
dessert --> {}
vehicles --> trucks --> {}
vehicles --> cars --> brands --> german brands --> Audi
vehicles --> cars --> brands --> german brands --> BMW
vehicles --> cars --> brands --> american brands --> Dodge
vehicles --> cars --> brands --> american brands --> Chevy
vehicles --> cars --> seats --> types --> leather
vehicles --> color--> black
vehicles --> color--> white
electronics --> laptops --> {}

我的代码可以做到这一点,但它只检查最终值是否是一个列表并打印列表及其关联的键(它不打印之前导致它的嵌套键, 与值关联的键)。

<table style="width:100%">
  <tr>
    <th>Nested Items Table</th>
  </tr>
  {% for key, value in _.x.items() recursive %}
    {% if value is mapping %}
      {{ loop(value.items()) }}
    {% else %}
      <tr>
      <td>{{ key }} --> {{ value }}</td>
      </tr>
    {% endif %}
  {% endfor %}
</table>

如果你运行上面的代码,我想你会明白我的意思。如果有人能够帮助我,或者可能引导我朝着正确的方向前进,我将不胜感激!

【问题讨论】:

    标签: python jinja2


    【解决方案1】:

    我建议你使用自定义过滤器来避免 jinja2 中的递归错误:(这里是循环)

    import jinja2
    
    x = {
          "food": {},
          "dessert": {},
          "vehicles": {
            "trucks": {},
            "cars": {
              "brands": {
                "german brands": ["Audi", "BMW"],
                "american brands": ["Dodge", "Chevy"]
              },
              "seats": {
                "types": ["leather"]
              }
            },
            "color": ["black", "white"]
          },
          "electronics": {"laptops": {}}
      }
    
    
    def looping(z):
        """Custom filter"""
    
    
        def islist(v):
            return type(v) == list
    
        def isdict(v):
            return type(v) == dict
    
        def islord(v):
            return type(v) == dict or type(v) == list
    
        def loopover(v, kk):
            global result
            for key, value in v.items():
                k = "<td>" + key + " --> "
    
                if islord(value):
                    if value == {}:
                        result = result + kk + k + "{}" + '</td>\n'
    
                    elif value == []:
                        result = result + kk + k + "[]" + '</td>\n'
    
                    elif isdict(value):
                        loopover(value, k)
                    elif islist(value):
                        for it in value:
                            result = result + kk + it + '</td>\n'
    
                else:
                    result = result + kk + k + value + '</td>\n'
    
        loopover(z, "")
        return result
    
    result = ""
    loader = jinja2.FileSystemLoader(searchpath='.')
    env = jinja2.Environment(autoescape=True, loader=loader)
    env.filters['looping'] = looping
    
    temp = env.get_template('template.html')
    
    result = temp.render(x=x)  
    print(result)
    

    与程序python在同一文件夹中的文件template.html:

    <table style="width:100%">
      <tr>
        <th>Nested Items Table</th>
      </tr>
          <tr>
          {{x | looping|safe}}
          </tr>
    
    </table>
    

    结果:

    <table style="width:100%">
      <tr>
        <th>Nested Items Table</th>
      </tr>
          <tr>
          <td>food --> {}</td>
    <td>dessert --> {}</td>
    <td>vehicles --> <td>trucks --> {}</td>
    <td>brands --> Audi</td>
    <td>brands --> BMW</td>
    <td>brands --> Dodge</td>
    <td>brands --> Chevy</td>
    <td>seats --> leather</td>
    <td>vehicles --> black</td>
    <td>vehicles --> white</td>
    <td>electronics --> <td>laptops --> {}</td>
          </tr>
    </table>
    

    【讨论】:

      猜你喜欢
      • 2013-11-24
      • 1970-01-01
      • 1970-01-01
      • 2018-02-11
      • 2014-06-30
      • 1970-01-01
      • 2020-03-23
      • 2013-04-30
      相关资源
      最近更新 更多