I want to change the key of an entry in a Python dictionary.
Is there a straightforward way to do this?
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.
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.
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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With