Python Forum
Accessing a value of a dictionary with jinja....
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Accessing a value of a dictionary with jinja....
#1
Question 
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 ?
[Image: NfRQr9R.jpg]
Reply
#2
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'
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#3
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.
SpongeB0B likes this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [Solved] Browser won't parse text from yaml loaded into Jinja SpongeB0B 1 952 Jul-07-2022, 09:37 PM
Last Post: SpongeB0B
  Jinja sort values from request.form SpongeB0B 2 2,186 Jul-26-2020, 07:41 AM
Last Post: SpongeB0B
  how to create dynamic arguments to be passed in jinja template in url_for function? experimental 1 2,739 May-01-2020, 05:50 PM
Last Post: Larz60+
  Flask tutorial errors in jinja, auth undefined Ecniv 2 2,451 May-03-2019, 02:04 PM
Last Post: Ecniv
  flask sqlite jinja accessing and updating database help pascale 5 4,082 Feb-11-2019, 03:49 PM
Last Post: pascale
  display multiple sensors on webpage python flask jinja pascale 6 5,198 Jan-29-2019, 10:10 AM
Last Post: pascale

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020