Search code examples
iterationjinja2nested-datalist

jinja2 error 'list object' has no attribute 'items'


EDIT Upon finding the solution, I changed the title to better reflect the issue. Unstuckify's reply remains valid and relevant to the text of the question

I have a list of dictionaries that I want to loop through with Jinja2:

dict = [{'symbol': 'BTCUSDT', 'price': 59325.1234, 'Qty': 2501}, {'symbol': 'ETHUSDT', 'price': 55.12, 'Qty': 14}]

I've used the loop below (from here). I expected the outer 'for' statement to pick up the first item in the list (which would be a dict) and the inner 'for' loop to iterate through the k,v in the dict.

{% for dict_item in dict %}
    {% for key, value in dict_item.items() %}
        <h1>Key: {{key}}</h1>
        <h2>Value: {{value}}</h2>
    {% endfor %}
{% endfor %}

However, Jinja gives me the following error - which suggests Jinja doesn't recognise the elements in the list as dicts:

jinja2.exceptions.UndefinedError: 'list object' has no attribute 'items'

Even heavily simplifed I keep getting the same error:

{% for symbol in dict %}
    <h2>{{ symbol }}</h2>
{% endfor %}

The Jinja docs aren't detailed enough on this. I've also tried this and looked at this approach without success. Passing just a dict (not a list of dicts) works well.

Can anybody explain why I'm getting this error and suggest better code? Getting the same error message with different approaches leads me to think there's some fundamental error in my thinking, but I can't figure it out.


Solution

  • The issue wasn't with the code, but rather environmental - I changed the title of the question to better reflect the issue.

    It turns out that there was most probably an issue with the Flask install, as a re-install (largely) solved the issue - the code above (both in the question and the answer) works as expected.

    In addition, during debugging I noticed that Jinja2 in my environment doesn't like commented text in the HTML () and behaves in a non-deterministic way when this is present. Equal code will sometimes throw an error, sometimes it won't and the Jinja2 error message will point to commented out code.

    Python 3.9.6, Flask 2.0.1, Jinja2 3.0.1, Chrome 93.0.4577.63, PyCharm 2021.1 on Win10 Home 20H2 19042.1165