8

I want to insert a key behind a given key in a OrdedDict.

Example:

my_orderded_dict=OrderedDict([('one', 1), ('three', 3)])

I want 'two' --> 2 to get into the right place.

In my case I need to update the OrdedDict in-place.

Background

SortedDict of Django (which has an insert()) gets removed: https://code.djangoproject.com/wiki/SortedDict

guettli
  • 25,042
  • 81
  • 346
  • 663
  • 8
    The other SO question (http://stackoverflow.com/questions/16664874/how-can-i-add-the-element-at-the-top-of-ordereddict-in-python) does not handle the `in place` update. I don't think my question is an duplicate. – guettli Mar 25 '15 at 08:19

1 Answers1

7
from collections import OrderedDict # SortedDict of Django gets removed: https://code.djangoproject.com/wiki/SortedDict

my_orderded_dict=OrderedDict([('one', 1), ('three', 3)])

new_orderded_dict=my_orderded_dict.__class__()
for key, value in my_orderded_dict.items():
    new_orderded_dict[key]=value
    if key=='one':
        new_orderded_dict['two']=2
my_orderded_dict.clear()
my_orderded_dict.update(new_orderded_dict)
print my_orderded_dict
guettli
  • 25,042
  • 81
  • 346
  • 663
  • this example code does successfully allow inserting new items in-place, however the code is prohibitively slow ([as noted by @AshwiniChaudhary's answer](https://stackoverflow.com/a/16664932/52074)) because the code creates a new `collections.OrderedDict` and then does a `clear` on the old dictionary then an `update` on the old `OrderedDict` (clearing the old dictionary and updating is expensive because clearing involves iterating and deleting all items. updating is expensive because it involves iterating over both the old/new and inserting.). – Trevor Boyd Smith Jun 07 '17 at 14:04
  • @TrevorBoydSmith feel free to update my code to a increase performance. If you are unsure, write me your idea first. I will look at it. – guettli Jun 07 '17 at 15:40
  • 1
    I upvoted your solution :). I was only warning unsuspecting future persons who might not be aware of the the performance implications. (The "prohibitively slow" part isn't your implementation. Your implementation is good enough given the requirements and the ordered dictionary's API... so again nothing wrong with your limitation.) – Trevor Boyd Smith Jun 07 '17 at 19:12