2

So I have a nested dictionary in the form of the following:

data =  { server:{'rating':{'class':'good, 'desc':'whatever'}, 'vulnerabilities':{'heartbleed':{'severity':'critical', 'desc':'terrible config'}}

I want to iterate through the values using keys, I've read the documentations and this is what I do in template:

  {% for key, value in data.items %}
      <p> 'This is the key {{ key }} and this is the value {{value}}'<p>
  {% endfor %}

so far so good, the bizarre thing is that I can`t get the values using the key retrieved by the for loop, namely, when I have such a template:

  {% for key in data.keys %}]
       <p> 'This is the key: {{key}}' </p> 
       <p> 'This is the value: {{ data.key }}'<p>
  {% endfor %}

{{key}} returns the keys with no problem. Even when I do {{data.server}} I get the corresponding values with no problem. Strange thing is that this line {{data.key}} does not work as I intuit it to.

In one loop the key==server, {{data.server}} works but {{data.key}} does not. What am I getting wrong here?

Slam
  • 8,112
  • 1
  • 36
  • 44
Amir Afianian
  • 2,679
  • 4
  • 22
  • 46
  • 1
    Because your dictionary has no key called `'key'`? It does have a key `'server'`, which is why that one works. You will have to use the django equivalent of `data[key]`, instead of `data['key']`, which is what it is doing now. – Graipher Mar 04 '18 at 08:59
  • @Graipher tnx, now I get it why it doesn't work. Does django have an equivalent for data[key]? – Amir Afianian Mar 04 '18 at 09:05
  • Sorry, I don't know anything about django. But I'm sure there is a way. – Graipher Mar 04 '18 at 09:06
  • I can't understand why you'd want to do this though, when iterating through `.items` works. – Daniel Roseman Mar 04 '18 at 09:17
  • @DanielRoseman my actual dictionary is far more complicated than this. Each initial key has a {rating:rating} of its own which I want to use to style the corresponding container ... – Amir Afianian Mar 04 '18 at 09:20

1 Answers1

1

Only way to this dynamically in template engine is to use custom template filter

Take a look at Django template how to look up a dictionary value with a variable for primer implementation

Slam
  • 8,112
  • 1
  • 36
  • 44