pemfir
pemfir

Reputation: 365

How to preserve the ordering of keys when declaring a dictionary

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?

Upvotes: 2

Views: 113

Answers (2)

mgilson
mgilson

Reputation: 310237

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'], '*')

Upvotes: 4

pemfir
pemfir

Reputation: 365

Based on thefourtheye response the solution is as follows:

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

Upvotes: 0

Related Questions