Replacing Items in Python Lists, Dicts, and OrderedDicts
Replace a value in a list
1 | index = items.index(old_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 | d[data_new] = 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 | from collections import OrderedDict |
Reference: