-4
sorted_event_types={}
        for key,value in sorted(event_types.items()):
            sorted_event_types[key]=value


(Pdb) print sorted_event_types
{'ch': 1, 'eh': 2, 'oh': 3, 'ah': 0, 'as': 1, 'cs': 0, 'os': 5, 'es': 9}
(Pdb) event_types
{'as': 1, 'ch': 1, 'eh': 2, 'oh': 3, 'cs': 0, 'ah': 0, 'os': 5, 'es': 9}

I want to sort a dictionary and keep it that way.

The output should be {'ah': 1, 'as': 1, 'ch': 2, 'cs': 3, 'eh': 0, ...}

Abhishek Bhatia
  • 9,404
  • 26
  • 87
  • 142
  • 3
    So what exactly is the question? – Mureinik Sep 17 '15 at 06:43
  • See [OrderedDict](https://docs.python.org/3/library/collections.html#collections.OrderedDict) (although I would probably turn it into a list instead, as I like the separation) – user2864740 Sep 17 '15 at 06:44
  • Sadly the duplicate question has OrderedDict (whether or not it is appropriate) answers rather buried.. – user2864740 Sep 17 '15 at 06:48
  • IMHO the duplicate question is not related with what OP is asking. I think [this one](http://stackoverflow.com/questions/1867861/python-dictionary-keep-keys-values-in-same-order-as-declared) is more relevant. – Ozgur Vatansever Sep 17 '15 at 06:52

2 Answers2

3

Dictionaries are unordered collections. You can create collections.OrderedDict with your sorted data to keep the order:

>>> import collections
>>> sorted_event_types = collections.OrderedDict(sorted(event_types.items()))
>>> print sorted_event_types
OrderedDict([('ah', 0), ('as', 1), ('ch', 1), ('cs', 0), ('eh', 2), ('es', 9), ('oh', 3), ('os', 5)])
Ozgur Vatansever
  • 49,246
  • 17
  • 84
  • 119
2

Dictionaries do not have any sense of order, they are unordered collections of key:value pairs.

If you want to maintain the order, you should use collections.OrderedDict . Example -

import collections
sorted_event_types = collections.OrderedDict()
for key,value in sorted(event_types.items()):
    sorted_event_types[key]=value
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176