Python replace dictionary key | Example code

Using the pop() or zip() function we can replace the dictionary key in Python. Even using the del keyword this is possible.

Examples of replace dictionary key in Python

A simple example changes the key of an entry in a Python dictionary.

Using basic and del keyword

Easily done in 2 steps:

dic1 = {'A': 1, 'B': 5, 'C': 10, 'D': 15}


# changing 'A' key
dic1['Z'] = dic1['A']
del dic1['A']

print(dic1)

Output:

Python replace dictionary key

Using pop() function

It will take one step only.

dic1 = {'A': 1, 'B': 5, 'C': 10, 'D': 15}

# changing 'A' key
dic1['Z'] = dic1.pop('A')

print(dic1)

Output: {‘B’: 5, ‘C’: 10, ‘D’: 15, ‘Z’: 1}

Using zip() function

Let’s replace all keys of the dictionary. But this will create a new dictionary.

dic1 = {'A': 1, 'B': 5, 'C': 10, 'D': 15}
kyes = ['X', 'Y', 'Z']

res = dict(zip(kyes, list(dic1.values())))

print(res)

Output: {‘X’: 1, ‘Y’: 5, ‘Z’: 10}

Do comment if you have any doubts and suggestions on this Python dictionary code.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.