Reputation: 365
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
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
Reputation: 365
Based on thefourtheye response the solution is as follows:
modelConfigBase = OrderedDict([('EC', '*'), ('ST', '*'), ('FC', '*'), ('MP', '*'), ('LP', '*'), ('SC', '*')])
Upvotes: 0