Python Forum

Full Version: Accessing a value of a dictionary with jinja....
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi everyone,

I have a nested dictionary like this (inside my python flask file)

{"content":[{"A":"blablabala"},{"A":"blublublu"}]}
listed as DICT here after

So I need to grab "blablabala" without knowing what will be the Key (A)

inside my Jinja template I've tried

{{ DICT["content"][0] }}
but this of course return me the full nested dictionary
{"A": "blablabla"}

I've tried then in the Jinja template
{%- set extraction = list(DICT["content"][0].values())  %}
{{ extraction[0] }}
But this give me the following error
jinja2.exception.UndefinedError: 'list' is undefined
Dodgy any ideas ?
I am not familiar with Jinja but in vanilla Python it works as expected:

>>> d = {"content":[{"A":"blablabala"},{"A":"blublublu"}]}
>>> list(d['content'][0].values())[0]
'blablabala'
Or alternatively with get method:

>>> list(d.get('content')[0].values())[0]
'blablabala'
That doesn't help the OP, since they're writing templates in Jinja for a web app (Jinja is used by default in Flask, as they mentioned).

Having said that, Jinja (and other templating languages) aren't meant to be too complex (it would be really bad for readability if you had a lot of logic in your templates, for example). So, you should really transform your data into a simple form that can be used in the template as-is.