0

I have an existing OrderedDict dictionary and I want to print out the keys in the original order of the dictionary.

All the key/value pairs were created at one time not one at a time like in most other examples on stackoverflow.

Here is the code:

test_dict = collections.OrderedDict()
test_dict = {
    'a':'A',
    'e':'E',
    'c':'C'

}

for key in test_dict:
    print key

And I get the result:

a
c
e

But I want to get:

a
e
c

Why is OrderedDict not keeping the original order? Is there any other way to keep original order of an existing dictionary?

nealous3
  • 712
  • 1
  • 11
  • 20
  • 8
    You overwrote the `OrderedDict` with a new `dict` in line two. – Klaus D. Sep 01 '16 at 07:43
  • 2
    You may find this article helpful: [Facts and myths about Python names and values](http://nedbatchelder.com/text/names.html), which was written by SO veteran Ned Batchelder. – PM 2Ring Sep 01 '16 at 07:53
  • 1
    The closest thing you can get to `dict` literal syntax is something like `test_dict = collections.OrderedDict(a='A', b='B, c='C')` – juanpa.arrivillaga Sep 01 '16 at 08:00
  • Thanks Klaus, PM 2Ring and juanpa. I even tried `test_dict = collections.OrderedDict({'a':'A','e':'E','c':'C'})` but is still out of order. So instead I read in a json file `r = json.load(open('practice.json'), object_pairs_hook=OrderedDict)` and printed `print json.dumps(r)` which worked perfectly. Thanks. – nealous3 Sep 02 '16 at 00:26

0 Answers0