Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the name of a key in dictionary

I want to change the key of an entry in a Python dictionary.

Is there a straightforward way to do this?

like image 940
user469652 Avatar asked Dec 10 '10 07:12

user469652


People also ask

How do you change the value of a key in a dictionary?

dict has no method to change the key, so add a new item with the new key and the original value, and then remove the old item.

How do I change the value of a key in Python?

Change Dictionary Values in Python Using the dict. update() Method. In this method, we pass the new key-value pairs to the update() method of the dictionary object. We can change one and more key-value pairs using the dict.

Can we modify keys in a dictionary if yes how?

Keys cannot be changed. You will need to add a new key with the modified value then remove the old one, or create a new dict with a dict comprehension or the like.

How do you edit a dictionary in Python?

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.


2 Answers

Easily done in 2 steps:

dictionary[new_key] = dictionary[old_key] del dictionary[old_key] 

Or in 1 step:

dictionary[new_key] = dictionary.pop(old_key) 

which will raise KeyError if dictionary[old_key] is undefined. Note that this will delete dictionary[old_key].

>>> dictionary = { 1: 'one', 2:'two', 3:'three' } >>> dictionary['ONE'] = dictionary.pop(1) >>> dictionary {2: 'two', 3: 'three', 'ONE': 'one'} >>> dictionary['ONE'] = dictionary.pop(1) Traceback (most recent call last):   File "<input>", line 1, in <module> KeyError: 1 
like image 176
moinudin Avatar answered Sep 28 '22 15:09

moinudin


if you want to change all the keys:

d = {'x':1, 'y':2, 'z':3} d1 = {'x':'a', 'y':'b', 'z':'c'}  In [10]: dict((d1[key], value) for (key, value) in d.items()) Out[10]: {'a': 1, 'b': 2, 'c': 3} 

if you want to change single key: You can go with any of the above suggestion.

like image 20
Tauquir Avatar answered Sep 28 '22 15:09

Tauquir