Q:

For Loop in python keeps changing the index

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

A:

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

