1

I want to do the same thins in this post reverse dictionary order . I didn't understand how to use OrderedDict. I tried this code with the dict() method used on the reversed list but It gave me the initial dictionary.

mydic = {'n1': 3, 'n2': 9}
ol = mydic.items()
ol.reverse()
print(ol)
dc = dict(ol)
print(dc)

as a result I get :

ol >> [('n2', 9), ('n1', 3)]
dc >> {'n1': 3, 'n2': 9}

Is there a way to rebuilt the dictionary after reversing the order ?

Thanks in advance

1
  • 2
    There's no such thing like order in dictionaries. Dec 17, 2012 at 23:19

3 Answers 3

2

Regular Python dictionaries don't preserve any order, so rearranging the keys won't do anything useful.

That being said, OrderedDict is really simple to use:

>>> from collections import OrderedDict
>>> 
>>> ol = [('n2', 9), ('n1', 3)]
>>> dc = OrderedDict(ol)
>>> dc
OrderedDict([('n2', 9), ('n1', 3)])
1
  • +1. And you can reverse an OrderedDict just by doing OrderedDict(reversed(dc.items())) (or the sequence of steps that the OP used, just substituting OrderedDict for dict).
    – abarnert
    Dec 17, 2012 at 23:41
2

The main issue with your approach is that the original dict does not guarantee any particular ordering of its keys. While you can get a snapshot of the mydic's items, reverse the order, and store the result in an OrderedDict, the output of that would be undefined (since the input is undefined).

In other words, garbage in garbage out.

If you are starting with an iterable of key-value pairs, then you could use OrderedDict:

In [18]: ol = [('n2', 9), ('n1', 3)]

In [19]: OrderedDict(reversed(ol))
Out[19]: OrderedDict([('n1', 3), ('n2', 9)])
0

Use collections.OrderedDict

Ordered dictionaries are just like regular dictionaries but they remember the order that items were inserted. When iterating over an ordered dictionary, the items are returned in the order their keys were first added.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.