Replacing Items in Python Lists, Dicts, and OrderedDicts

Replace a value in a list

1
2
index = items.index(old_value)
items[index] = new_value

Rename a dict key

Pop the old key and assign the new one:

1
d[data_new] = d.pop(data_old)

pop() removes and returns the value. If you do not need the return value:

1
2
d[data_new] = d[data_old]
del d[data_old]

Note: when looping, copying dict.keys() first prevents the loop from seeing the newly inserted key.

Rename an OrderedDict key

OrderedDict preserves insertion order. Calling d[new] = d.pop(old) will move the key to the end. Rebuild the mapping instead:

1
2
3
4
5
from collections import OrderedDict

new_order = OrderedDict(
[('__C__', v) if k == 'c' else (k, v) for k, v in old_order.items()]
)

Reference:

《change key in OrderedDict without losing order》