2

My goal is to preserve the ordering of keys in a dictionary declaration. I am using collections.OrderedDict but when I run:

>>> modelConfigBase = OrderedDict({'FC':'*','EC':'*','MP':'*','LP':'*','ST':'*','SC':'*'})

The order changes:

>>> modelConfigBase
OrderedDict([('EC', '*'), ('ST', '*'), ('FC', '*'), ('MP', '*'), ('LP', '*'), ('SC', '*')])

What am I doing wrong?

Air
  • 8,274
  • 2
  • 53
  • 88
pemfir
  • 365
  • 1
  • 3
  • 10
  • 1
    Once the dictionary is created, there is no key ordereing. In your case, the dictionary which is created already is passed to `OrderedDict` – thefourtheye Jan 15 '16 at 18:27
  • The repr value that prints in the interactive interpreter shows you how to create the object. In this case, use a list of tuples. – Air Jan 15 '16 at 18:35
  • Duplicate of [Converting Dict() to OrderedDict()](http://stackoverflow.com/questions/15711755/converting-dict-to-ordereddict) – SirParselot Jan 15 '16 at 18:36

2 Answers2

4

The dictionary that you are passing to OrderedDict is unordered. You need to pass an ordered iterable of items . . .

e.g.

modelConfigBase = OrderedDict([
    ('FC', '*'),
    ('EC', '*'),
    ('MP', '*'),
    ('LP', '*'),
    ('ST', '*'),
    ('SC', '*')])

Note that, in this case (since all the values are the same), it looks like you could get away with the simpler:

modelConfigBase = OrderedDict.fromkeys(['FC', 'EC', 'MP', 'LP', 'ST', 'SC'], '*')
mgilson
  • 300,191
  • 65
  • 633
  • 696
0

Based on thefourtheye response the solution is as follows:

modelConfigBase = OrderedDict([('EC', '*'), ('ST', '*'), ('FC', '*'), ('MP', '*'), ('LP', '*'), ('SC', '*')])
pemfir
  • 365
  • 1
  • 3
  • 10