change key in OrderedDict without losing order

frnhr picture frnhr · Aug 28, 2012 · Viewed 12.5k times · Source

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?

Answer

MRAB picture MRAB · Aug 28, 2012

You could try:

>>> d = OrderedDict([('a', 1), ('c', 3), ('b', 2)])
>>> d
OrderedDict([('a', 1), ('c', 3), ('b', 2)])
>>> d2 = OrderedDict([('__C__', v) if k == 'c' else (k, v) for k, v in d.items()])
>>> d2
OrderedDict([('a', 1), ('__C__', 3), ('b', 2)])