I have a dictionary like this in django
my_dict = {0: 'Dog - Wikipedia',
1: 'https://en.wikipedia.org/wiki/Dog',
2: 'Funny babies annoying dogs - Cute dog & baby compilation ...',
3: 'https://www.youtube.com/watch?v=M1djO19aSFQ'}
What I want is to have title as title but the link to be appeared as a link in html template...Can u guys please help me sort this out?i am new in this case.. :(
ps: how do i iterate over the dictionary to create one as a title and the next one as a link?
-
1This is a very strange format for storing pairs of items. How did the dictionary come about and can we change its format at the source?Alex Hall– Alex Hall2018年04月27日 16:57:22 +00:00Commented Apr 27, 2018 at 16:57
2 Answers 2
That will be something like this:
{% for k, v in my_dict.items %)
{% if k == 0 %} <h1>{{ v }}</h1> {% endif %}
{% elif k == 1 %} <a href="{{ v }}">Some link text</a> {% endif %}
{% endfor %}
Learn more about Django Template Tags.
3 Comments
To be clear, you want to take that dictionary and make a new dictionary that contains the title as the key value and the url as the value of the key? If so, the following should do the trick.
new_dict = {}
for i in range(len(my_dict.values())):
if not i%2:
new_dict[my_dict[i]] = my_dict[i+1]
Or you can write it pythonically with a dict comprehension.
newer_dict = { my_dict[i]:my_dict[i+1] for i in range(len(my_dict.values())) if not i%2 }