+2 votes
in Programming Languages by (73.8k points)

I want to change some of the keys in a dictionary. How can I do that?

E.g.

aa = {'a':1,'b':2,'c':3,'f':4} to

aa = {'a':1,'b':2,'c':3,'d':4}

1 Answer

+2 votes
by (348k points)
selected by
 
Best answer

You can change the key of a dictionary using one of the following two ways:

Approach 1

your_dictionary[new_key] = your_dictionary[old_key]
del your_dictionary[old_key]

Approach 2
your_dictionary[new_key] = your_dictionary.pop(old_key)

Example:

Approach 1

>>> aa = {'a':1,'b':2,'c':3,'f':4}
>>> aa
{'a': 1, 'b': 2, 'c': 3, 'f': 4}
>>> aa['d']=aa.pop('f')
>>> aa
{'a': 1, 'b': 2, 'c': 3, 'd': 4}

Approach 2

>>> aa = {'a':1,'b':2,'c':3,'f':4}
>>> aa['d']=aa['f']
>>> del aa['f']
>>> aa
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
>>>


...