Python dictionary is not staying in order
python, python-2.7, python-3.x
Solution
Update for Python 3.7+:
Dictionaries now officially maintain insertion order for Python 3.7 and above.
Update for Python 3.6:
Dictionaries maintain insertion order in Python 3.6, however, this is considered an implementation detail and should not be relied upon.
Original answer - up to and including Python 3.5:
Dictionaries are not ordered and don't keep any order for you.
You could use an ordered dictionary, which maintains insertion order:
from collections import OrderedDict
letterDict = OrderedDict([('a', 0), ('b', 0), ('c', 0)])
Or you could just return a sorted list of your dictionary contents
letterDict = {'a':0,'b':0,'c':0}
sortedList = sorted([(k, v) for k, v in letterDict.iteritems()])
print sortedList # [('a', 0), ('b', 0), ('c', 0)]
Problem
I created a dictionary of the alphabet with a value starting at 0, and is increased by a certain amount depending on the word file. I hard coded the initial dictionary and I wanted it to stay in alphabetical order but it does not at all. I want it to return the dictionary in alphabetical order, basically staying the same as the initial dictionary. How can i keep it in order? ``` from wordData import* def letterFreq(words): totalLetters = 0 letterDict = {'a':0,'b':0,'c':0,'d':0,'e':0,'f':0,'g':0,'h':0,'i':0,'j':0,'k':0,'l':0,'m':0,'n':0,'o':0,'p':0,'q':0, 'r':0,'s':0,'t':0,'u':0,'v':0,'w':0,'x':0,'y':0,'z':0} for word in words: totalLetters += totalOccurences(word,words)*len(word) for char in range(0,len(word)): for letter in letterDict: if letter == word[char]: for year in words[word]: letterDict[letter] += year.count for letters in letterDict: letterDict[letters] = float(letterDict[letters] / totalLetters) print(letterDict) return letterDict def main(): filename = input("Enter filename: ") words = readWordFile(filename) letterFreq(words) if __name__ == '__main__': main() ```