Python Forum
Accessing a value of a dictionary with jinja.... - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Web Scraping & Web Development (https://python-forum.io/forum-13.html)
+--- Thread: Accessing a value of a dictionary with jinja.... (/thread-34515.html)



Accessing a value of a dictionary with jinja.... - SpongeB0B - Aug-06-2021

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 ?


RE: Accessing a value of a dictionary with jinja.... - perfringo - Aug-06-2021

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'



RE: Accessing a value of a dictionary with jinja.... - ndc85430 - Aug-06-2021

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.