Dictionary does not have any sense of order , so your key/value pairs are not ordered in any format.
If you want to preserve the order of the keys, you should use collections.OrderedDict
from the start, instead of using normal dictionary , Example -
>>> from collections import OrderedDict
>>> d = OrderedDict([('a',1),('b',2),('c',3)])
>>> d
OrderedDict([('a', 1), ('b', 2), ('c', 3)])
OrderedDict would preserve the order in which the keys were entered into the dictionary. In above case, it would be the order in which the keys existed in the list - [('a',1),('b',2),('c',3)]
- 'a' -> 'b' -> 'c'
Then you can get the reversed order of keys using reversed(d)
, Example -
>>> dreversed = OrderedDict()
>>> for k in reversed(d):
... dreversed[k] = d[k]
...
>>> dreversed
OrderedDict([('c', 3), ('b', 2), ('a', 1)])