0

I have this loop to create the nav bar. It's working except the arrangement of the links keeps changing every time i run the program

nav ={'page1':'page1.html','page2': 'page2.html','page3':'page3.html','page4':'page4.html','page5':'page5.html'}
output= ""
for key in nav:
    if nav[key]==active:
        output+='<li class="active"><a href="%s">%s</a></li>' % (nav[key],key)
    else:
        linksHtml+='<li><a href="%s">%s</a></li>' % (nav[key],key)
return output
3
  • 5
    You're using a dictionary, dictionaries are unordered. Commented Jun 18, 2017 at 19:34
  • what do i do then? Commented Jun 18, 2017 at 19:34
  • You could just extract the keys and order them before iterating: keys = sorted(list(nav.keys())) Commented Jun 18, 2017 at 19:54

2 Answers 2

1

Using the collections package OrderedDict method you can ensure they always come out in the same order you originally added them. See https://docs.python.org/2/library/collections.html#collections.OrderedDict for more detaills.

import collections

nav ={'page1':'page1.html','page2': 'page2.html','page3':'page3.html','page4':'page4.html','page5':'page5.html'}
output= ""
for key in collections.OrderedDict(nav):
    if nav[key]==active:
        output+='<li class="active"><a href="%s">%s</a></li>' % (nav[key],key)
    else:
        linksHtml+='<li><a href="%s">%s</a></li>' % (nav[key],key)
return output
Sign up to request clarification or add additional context in comments.

Comments

1

You can use OrderDict if you want to keep the order of insertion.

Comments

Your Answer

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.