Rajeev
Rajeev

Reputation: 46919

get key value from a dictionary django/python

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

Upvotes: 4

Views: 7235

Answers (2)

jonescb
jonescb

Reputation: 22771

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.

Upvotes: 1

AndiDog
AndiDog

Reputation: 70158

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.

Upvotes: 14

Related Questions