1

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?

Alex Hall
36.2k5 gold badges63 silver badges98 bronze badges
asked Apr 27, 2018 at 16:52
1
  • 1
    This 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? Commented Apr 27, 2018 at 16:57

2 Answers 2

1

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.

Geancarlo Murillo
5171 gold badge5 silver badges15 bronze badges
answered Apr 27, 2018 at 17:41
Sign up to request clarification or add additional context in comments.

3 Comments

I will appreciate if you accept the answer if it helped :)
So you can mark this answer as the right answer - just press that grey tick below arrows to the left from this answer ))
Yes, that worked, thank you :) that points help users to do more things on this site :)
0

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 }
answered Apr 27, 2018 at 17:35

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.