Get key value from django / python dictionary

How to print the key value from the key itself

dict={} dict.update({'aa':1}) dict.update({'ab':1}) dict.update({'ac':1}) return render_to_response(t.html, context_instance=RequestContext(request, {'dict':dict})) 

So, in this case, I want to print the alert('{{dict.aa}}'); key alert('{{dict.aa}}'); , i.e. without using any loop, we can simply print the key with a link to aa in the above example, maybe something like if {{dict ['aa']}} should indicate the value aa

+4
source share
2 answers

Never call a dict dictionary that will overwrite the built-in name of type dict in the current scope.

You can access the keys and values ​​in the template as follows:

 {% for item in d.items %} key = {{ item.0 }} value = {{ item.1 }} {% endfor %} 

or use d.keys if you only need keys.

+14
source

If you are doing what I think you are doing, you should not use a dictionary. The parameters you pass to the template are already in the dictionary. If you are not going to iterate over them, you better put the keys directly in the template parameters.

  return render_to_response(t.html, context_instance=RequestContext(request, {'aa':1, 'ab': 1, 'ac':1})) 

And now it’s very easy to refer to them in your template.

 {{ aa }} {{ ab }} {{ ac }} 

If you really need to iterate over an arbitrary dictionary, then AndiDog's answer is correct.

+1
source

Source: https://habr.com/ru/post/1342633/


All Articles