get key value from a dictionary django/python

我的梦境 提交于 2019-12-10 16:17:51

问题


How to print the value of a key 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 key alert('{{dict.aa}}'); i.e,without using any loop can we just print the key with the reference of aa in the the above example may some thing like if {{dict['aa']}} should give the value of aa


回答1:


Never call a dictionary dict, that would overwrite the builtin dict type name in the current scope.

You can access keys and values in the template like so:

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

or use d.keys if you only need the keys.




回答2:


If you're doing what I think you're doing, you shouldn't be using a dictionary. The parameters you're passing to the template are already in a dictionary. If you're not going to loop over them you're better off putting the keys directly into the template parameters.

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

And now it's really easy to reference them in your template.

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

If you do actually need to loop over an arbitrary dictionary, then AndiDog's answer is correct.



来源:https://stackoverflow.com/questions/5220355/get-key-value-from-a-dictionary-django-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!