+1 vote
in Programming Languages by (7k 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

0 votes
by (13.5k points)

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}
>>>

...