-1

I'm having problems with this Python 2.7 code:

singlelower = string.ascii_lowercase
lowerdict = {}
for i in singlelower:
     lowerdict[i] = i

I want this to return a dictionary in which each key and value are alike, and all keys are in alphabetical order. It creates the dictionary, but is out of order, even though the for loop should be stepping through the string alphabetically. Here's the output:

{'a': 'a', 'c': 'c', 'b': 'b', 'e': 'e', 'd': 'd', 'g': 'g', 'f': 'f', 'i': 'i', 'h': 'h', 'k': 'k', 'j': 'j', 'm': 'm', 'l': 'l', 'o': 'o', 'n': 'n', 'q': 'q', 'p': 'p', 's': 's', 'r': 'r', 'u': 'u', 't': 't', 'w': 'w', 'v': 'v', 'y': 'y', 'x': 'x', 'z': 'z'}

As you can see the dictionary is in reverse pairs. Am I overlooking something with the implementation?

cortman
  • 3
  • 1
  • 4
    Dictionaries are inherently unordered, by design. You won't get any alphabetical order out of them. – TheSoundDefense Jul 27 '14 at 01:27
  • why do you need the dictionary in order? – Josh Engelsma Jul 27 '14 at 01:29
  • Thanks for pointing that out. I guess I thought it would keep the elements in the order they were added, in which case it should be alphabetical (per my for loop), right? – cortman Jul 27 '14 at 01:33
  • @cortman if that were the case, then yes, it would be output in alphabetical order. But a dictionary's contents are stored as a hash table under the hood, which allows for very fast access but no preserved ordering. – TheSoundDefense Jul 27 '14 at 01:36
  • @Martijn Pieters- thanks for adding the link, that explains my question a little better. Essentially, Python will sort the dictionary into an order that makes for most efficient search and retrieval. – cortman Jul 27 '14 at 01:37
  • @cortman: the order you see is an *artifact* of how key-value pairs are stored. See [Why is the order in Python dictionaries arbitrary?](http://stackoverflow.com/q/15479928). The dictionary cares little about the order. – Martijn Pieters Jul 27 '14 at 01:38

1 Answers1

1

If there is a compelling reason to have the dictionary in order, use collections.OrderedDict(). It is a subclass of dict, so it supports all the operations you'd expect from a normal dictionary.

from collections import OrderedDict
import string

lowerdict = OrderedDict()
for char in string.ascii_lowercase:
    lowerdict[char] = char


>>> print(lowerdict)
OrderedDict([('a', 'a'), ('b', 'b'), ('c', 'c'), ('d', 'd'), ('e', 'e'), ('f', 'f'), ('g', 'g'), ('h', 'h'), ('i', 'i'), ('j', 'j'), ('k', 'k'), ('l', 'l'), ('m', 'm'), ('n', 'n'), ('o', 'o'), ('p', 'p'), ('q', 'q'), ('r', 'r'), ('s', 's'), ('t', 't'), ('u', 'u'), ('v', 'v'), ('w', 'w'), ('x', 'x'), ('y', 'y'), ('z', 'z')])
MattDMo
  • 100,794
  • 21
  • 241
  • 231