update key in python dictionary

How to Update Key in Dictionary in Python

Python dictionaries allow you to store different data types in a compact structure. Sometimes you may need to update key of your dictionary in Python. In this article, we will look at how to modify dictionary keys in Python.


How to Update Key in Dictionary in Python

Here are three different ways to update key in dictionary in python. Let us say you have the following dictionary.

>>> data={'a':1,'b':2,'c':3}
>>> data
{'a': 1, 'c': 3, 'b': 2}


1. Using temporary element

In this approach we create another dictionary item with same value as that of item whose key you want to change. Then we delete the original element. Here is an example to replace key a with d.

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


2. Using pop() function

Pop function removes an item from dictionary but also returns its value at the same time. So you can also use pop() function to copy an item’s value to another item with new key.

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

3. Using zip method

Sometimes you may need to update multiple keys at one go. In such cases, you can use zip function to quickly bulk update keys. Let us say you have new keys in list new_keys as shown below.

>>> data={'a':1,'b':2,'c':3}
>>> data
{'a': 1, 'c': 3, 'b': 2}
>>> new_keys=['a1','b1','c1']
>>> data = dict(zip(new_keys, data.values()))
>>> data
{'a1': 1, 'c1': 3, 'b1': 2}

In this case, we create a list of dict values using data.values() and use the zip function to create a new dictionary using this list of values and new_keys list of new keys.

In this article, we have looked at three simple ways to update key in python dictionary. Out of them, the first two employ the same method of copying the value of an item with old key to another item with new key, and then deleting the item with old key. The last one uses a list of keys and list of values to create a completely new dictionary with new keys.

Also read:

How to Search Item in List of Dictionaries in Python
How to Remove Multiple Items from List in Python
How to Flatten List of Dictionaries in Python
How to Flatten List of Tuples in Python
How to Find & Delete Broken Symlinks

Leave a Reply

Your email address will not be published. Required fields are marked *