Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Renaming the keys of a dictionary [duplicate]

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
like image 385
BarryPye Avatar asked Jun 08 '15 23:06

BarryPye


People also ask

How do you change the name of a dictionary key?

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.

Can you duplicate keys in dictionaries?

First, a given key can appear in a dictionary only once. Duplicate keys are not allowed.

Can we change key name in dictionary Python?

Method 2: Rename a Key in a Python Dictionary using Python pop() We use the pop method to change the key value name.

Can a dictionary have two identical keys?

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.


1 Answers

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'}
like image 142
Bhargav Rao Avatar answered Oct 19 '22 19:10

Bhargav Rao