Python dictionaries how to keep them in order

I think of dictionaries as an associative array, so when I typed

dict1 = {'first' : 1, 'second' : 2} 

I was hoping when I call, it will be in the order in which it was written, but it is not. It was "second" to "first." I looked and realized that the dictionaries were disordered. So that makes sense, but I was wondering if there is a way to keep them in the same order that you wrote them (or added them)? All I'm looking for here is basically a list (which stays alright) that allows strings to be used as a key.

thanks

+4
source share
2 answers
 from collections import OrderedDict OrderedDict([("first", 1), ("second", 2)]) 

This works in Python> = 2.7, IIRC. For earlier versions, there are replacements available on the Internet, but storing the keys in a separate file is probably the easiest way.

+10
source

Python has an OrderedDict (in collections ) for this.

New in version 2.7

+4
source

All Articles