Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rename a dictionary key

Tags:

python

Is there a way to rename a dictionary key, without reassigning its value to a new name and removing the old name key; and without iterating through dict key/value?

In case of OrderedDict, do the same, while keeping that key's position.

like image 299
rabin utam Avatar asked May 10 '13 04:05

rabin utam


People also ask

How do you rename a dictionary key?

How to rename a key in a Python dictionary? To rename a Python dictionary key, use the dictionary pop() function to remove the old key from the dictionary and return its value. And then add the new key with the same value to the dictionary.

Can you modify the value in a dictionary?

Modifying a value in a dictionary is pretty similar to modifying an element in a list. You give the name of the dictionary and then the key in square brackets, and set that equal to the new value.


1 Answers

For a regular dict, you can use:

mydict[k_new] = mydict.pop(k_old) 

This will move the item to the end of the dict, unless k_new was already existing in which case it will overwrite the value in-place.

For a Python 3.7+ dict where you additionally want to preserve the ordering, the simplest is to rebuild an entirely new instance. For example, renaming key 2 to 'two':

>>> d = {0:0, 1:1, 2:2, 3:3} >>> {"two" if k == 2 else k:v for k,v in d.items()} {0: 0, 1: 1, 'two': 2, 3: 3} 

The same is true for an OrderedDict, where you can't use dict comprehension syntax, but you can use a generator expression:

OrderedDict((k_new if k == k_old else k, v) for k, v in od.items()) 

Modifying the key itself, as the question asks for, is impractical because keys are hashable which usually implies they're immutable and can't be modified.

like image 52
wim Avatar answered Oct 04 '22 01:10

wim