How to change a key in a Python dictionary?
A routine returns a dictionary. Everything is OK with the dictionary except a couple keys need to be renamed. This code below copies the dictionary entry (key=value) into a new entry with the desired key and then deletes the old entry. Is there a more Pythonic way, perhaps without duplicating the value?
my_dict = some_library.some_method(scan)
my_dict['qVec'] = my_dict['Q']
my_dict['rVec'] = my_dict['R']
del my_dict['Q'], my_dict['R']
return my_dict
Since keys are what dictionaries use to lookup values, you can't really change them. The closest thing you can do is to save the value associated with the old key, delete it, then add a new entry with the replacement key and the saved value.
First, a given key can appear in a dictionary only once. Duplicate keys are not allowed.
Method 2: Rename a Key in a Python Dictionary using Python pop() We use the pop method to change the key value name.
No, each key in a dictionary should be unique. You can't have two keys with the same value. Attempting to use the same key again will just overwrite the previous value stored. If a key needs to store multiple values, then the value associated with the key should be a list or another dictionary.
dict
keys are immutable. That means that they cannot be changed. You can read more from the docs
dictionaries are indexed by keys, which can be any immutable type
Here is a workaround using dict.pop
>>> d = {1:'a',2:'b'}
>>> d[3] = d.pop(1)
>>> d
{2: 'b', 3: 'a'}
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