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
Use OrderedDict.move_to_end() method. Using it, we can move an existing key to either end of the dictionary in O(1) time. If we need to insert an element and move it to the top, all in one step, we can directly use it to create a prepend() wrapper (not presented here).
Python's OrderedDict is a dict subclass that preserves the order in which key-value pairs, commonly known as items, are inserted into the dictionary. When you iterate over an OrderedDict object, items are traversed in the original order. If you update the value of an existing key, then the order remains unchanged.
Using next(reversed(od)) is a perfect way of accessing the most-recently added element. The class OrderedDict uses a doubly linked list for the dictionary items and implements __reversed__() , so this implementation gives you O(1) access to the desired element.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With