Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert into OrderedDict behind key "foo" (inplace) [duplicate]

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

like image 808
guettli Avatar asked Mar 25 '15 08:03

guettli


People also ask

How do I add an item to an ordered dictionary?

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).

What is OrderedDict ()?

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.

How do I get the last element of OrderedDict?

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.


1 Answers

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
like image 171
guettli Avatar answered Sep 28 '22 19:09

guettli