无法遍历字典,如何检查字典是否为空?

时间:2019-02-15 12:59:06

标签: ansible jinja2

我正在尝试为Web应用程序升级服务器,我必须遍历键值字典,但出现以下错误

FAILED! => {"changed": false, "msg": "AnsibleUndefinedVariable: 'ansible.utils.unsafe_proxy.AnsibleUnsafeText object' has no attribute 'iteritems'"}

我尝试过

    {  
      "version":"{{ version.actual_version_number }}",  
      "integrations": {  
    {% for id, port in integration_details.items() %}  
      {% if integration_details is defined and integration_details is not empty %}  
        {{ id }} : {{ port }}  
      {% endif %}  
      {%- if not loop.last -%},{% endif %}  
    {% endfor %}  
      }  
    }

如果有人可以帮助解决此问题,我们将不胜感激!

1 个答案:

答案 0 :(得分:0)

假设您的数据结构是字典,请使用if integration_details is defined and integration_details.keys()|length > 0,这将检查是否存在任何子项。如果其列表使用if integration_details is defined and integration_details|length > 0

但是看到您发布的错误,您可能在iteritems()某处有一个for循环,这不在您发布的代码中。

这可能是因为您使用python3,但想使用iteritems()而不是items()来迭代dict,或者您的变量不是dict而是其他类型。