Starting with
OrderedDict([('a', 1), ('c', 3), ('b', 2)])
is it possible to end up with
OrderedDict([('a', 1), ('__C__', 3), ('b', 2)])
making sure that the '__C__'
item is before 'b'
and after 'a'
i.e. keeping order?
Starting with
OrderedDict([('a', 1), ('c', 3), ('b', 2)])
is it possible to end up with
OrderedDict([('a', 1), ('__C__', 3), ('b', 2)])
making sure that the '__C__'
item is before 'b'
and after 'a'
i.e. keeping order?
You could try:
if you wish to mutate the current dictionary object:
This works by iterating over the whole
OrderedDict
(using its length), and pop'ing its first item (by passingFalse
to.popitem()
: the default of this method is to pop the last item) intok
andv
(respectively standing for key and value); and then inserting this key/value pair, or the new key with its original value, at the end of theOrderedDict
.By repeating this logic for the entire size of the dict, it effectively rotates the dict completely, thus recreating the original order.