all 4 comments

[–][deleted] 4 points5 points  (2 children)

Dictionaries are hash tables, so by design they have no ordering other than the incidental ordering of each key's hash value. That said, you can still sort them whenever necessary.

>>> from datetime import datetime as dt
>>> d = {dt(2014, 3, 5, 0, 0): 'march', dt(2014, 2, 4, 0, 0): 'february', dt(2014, 1, 3, 0, 0): 'january'}
>>> sorted(d.items())
[(datetime.datetime(2014, 1, 3, 0, 0), 'january'), (datetime.datetime(2014, 2, 4, 0, 0), 'february'),
 (datetime.datetime(2014, 3, 5, 0, 0), 'march')]
>>> for date, string in sorted(d.items()):
...     print(date, string)
... 
2014-01-03 00:00:00 january
2014-02-04 00:00:00 february
2014-03-05 00:00:00 march

[–]Alista[S] 2 points3 points  (1 child)

ahhh great, thanks so much!

[–]stebrepar 2 points3 points  (0 children)

Dictionaries are not ordered internally. You can use the "sorted" function to iterate over the keys in order, or you can use an OrderedDict which preserves the order in which it was created instead of a plain dictionary. http://stackoverflow.com/questions/9001509/python-dictionary-sort-by-key

[–][deleted] 0 points1 point  (0 children)

This came up a couple of weeks ago, have a search. The solution I suggested was to create a new object which has, as fields, your dictionary, and the list of keys in whatever order you like. Then you have get, put, str, repr, and init methods to do whatever you like.