打印可能存在或不存在的嵌套字典值 [英] Printing nested dictionary values that may or may not exist

查看:77
本文介绍了打印可能存在或不存在的嵌套字典值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Python(Django)中有一个嵌套的字典,就像这样:

I have a nested dictionary in Python (Django), like so:

books = 
 { 
   1: { 1: 'Alice', 2: 'Bob', 3: 'Marta' }, 
   2: { 1: 'Alice', 3: 'Marta' }, 
   3: { 1: 'Alice', 2: 'Bob' }, 
 }

现在,在我的模板中,我想打印一个特定的项目,但是仅当它存在时才打印,例如books [4] [1].但是如果我这样做,我会得到:

Now in my template I want to print a particular item, but only if it exists, for instance books[4][1]. But if I do this, I get:

{{ books[4][1] }}

Error: Could not parse the remainder

所以我要检查一下

{% if 4 in books %}
  {% if 1 in books[4] %}
     {{ books[4][1] %}
  {% endif %}
{% endif %}

这也不起作用,并给出了解析错误(无法解析其余部分).如果我不确定字典中是否存在嵌套的字典值,正确的方法是什么?

This also doesn't work and gives a parse error (Could not parse the remainder). What is the proper way to print a nested dictionary value in Django if I"m not sure if it exists in the dictionary?

推荐答案

Django模板语言在故意与Python代码不同,因此不鼓励人们向其中编写业务逻辑.

Django template language is deliberately different from Python code, such that people are discouraged to write business logic into it.

但是模板逻辑足够强大,可以通过用点表示法编写代码来对项目执行项目获取.例如:

But the template logic is strong enough to perform an item-getter on the items, by writing this in dot notation. For example:

{{ books[4][1] }}

应写为:

{{ books.4.1 }}

所以您可以这样写:

{% if 4 in books %}
  {% if 1 in books.4 %}
     {{ books.4.1 %}
  {% endif %}
{% endif %}

话虽这么说,所有这些查找根本没有必要.由于Django通常会在查找失败时 not 产生错误.在这种情况下,当需要打印时,它将回退到TEMPLATE_STRING_IF_INVALID字符串.默认情况下该字段为空,因此我们可以避免麻烦并写:

That being said, all these lookups are not necessary at all. Since Django typically will not produce an error if a lookup fails. In that case, it will fallback to the TEMPLATE_STRING_IF_INVALID string when it needs to print it. Which is by default empty, so we could avoid the trouble and write:

{{ books.4.1 }}

,如果元素存在,将打印settings.TEMPLATE_STRING_IF_INVALID(如果未指定,则为空字符串).

which will, in case the element does not exists, print the settings.TEMPLATE_STRING_IF_INVALID (if not specified, it is the empty string).

如果要执行检查,可以 直接在整个变量上使用if,例如:

In case you want to perform a check, you can use an if directly on the entire variable, like:

{% if books.4.1 %}
  {{ books.4.1 %}
{% endif %}

检查此模板变量"表达式是否得到解析,结果是否具有真实性 True.

to check if this "template variable" expressions gets resolved, and the result has truthiness True.

这篇关于打印可能存在或不存在的嵌套字典值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆