This post helps one get a better and deeper understanding on how to store and retrieve data from dictionary in Django Python.
Lets take a situation of combining two lists into dictionary,
Consider List A,
A = [ ‘Kruthika’,’Pooja’,’Priyanka’]
Now, Consider List B,
B = [36,99,101]
To map the names of the above students to their respective marks, we could use dictionary :)
combined_lists = dict(zip(A,B))
To render the above combined_lists dictionary to template in django python,
return render(request,’1.html',{'combined_lists':sorted(combined_lists.iteritems()) } )
.iteritems() helps in displaying of each character of value in dictionary along with its key value as the following :
1.html :
{% for name,marks in combined_lists %}
{{name}}:{{marks}}
{% endfor %}
Kruthika : 36
Pooja : 99
Priyanka : 101
Without .iteritems() , if dictionary is rendered as follows :
return render(request,’1.html',{'combined_lists':sorted(combined_lists) } )
1.html :
{% for name,marks in combined_lists %}
{{name}}:{{marks}}
{% endfor %}
Kruthika : 3
Pooja : 9
Priyanka : 1
No comments:
Post a Comment