Open In App

Python | Ways to change keys in dictionary

Last Updated : 27 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a dictionary, the task is to change the key based on the requirement. Let’s see different methods we can do this task in Python.

Example:

initial dictionary:  {'nikhil': 1, 'manjeet': 10, 'Amit': 15}
final dictionary:    {'nikhil': 1, 'manjeet': 10, 'Suraj': 15}
c: Amit name changed to Suraj.

Method 1: Rename a Key in a Python Dictionary using the naive method 

Here, we used the native method to assign the old key value to the new one.

Python3




# initialising dictionary
ini_dict = {'nikhil': 1, 'vashu': 5,
            'manjeet': 10, 'akshat': 15}
 
# printing initial json
print("initial 1st dictionary", ini_dict)
 
# changing keys of dictionary
ini_dict['akash'] = ini_dict['akshat']
del ini_dict['akshat']
 
 
# printing final result
print("final dictionary", str(ini_dict))


Output

initial 1st dictionary {'nikhil': 1, 'vashu': 5, 'manjeet': 10, 'akshat': 15}
final dictionary {'nikhil': 1, 'vashu': 5, 'manjeet': 10, 'akash': 15}

Time complexity: O(n), where n is the number of key-value pairs in the dictionary.
Auxiliary space: O(n), to store the keys and values in dictionary.

 Method 2: Rename a Key in a Python Dictionary using Python pop() 

We use the pop method to change the key value name.

Python3




# initialising dictionary
ini_dict = {'nikhil': 1, 'vashu': 5,
            'manjeet': 10, 'akshat': 15}
 
# printing initial json
print("initial 1st dictionary", ini_dict)
 
# changing keys of dictionary
ini_dict['akash'] = ini_dict.pop('akshat')
 
# printing final result
print("final dictionary", str(ini_dict))


Output

initial 1st dictionary {'nikhil': 1, 'vashu': 5, 'manjeet': 10, 'akshat': 15}
final dictionary {'nikhil': 1, 'vashu': 5, 'manjeet': 10, 'akash': 15}

 Method 3: Rename a Key in a Python Dictionary using Python zip() 

Suppose we want to change all keys of the dictionary.

Python3




# initialising dictionary
ini_dict = {'nikhil': 1, 'vashu': 5,
            'manjeet': 10, 'akshat': 15}
 
# initialising list
ini_list = ['a', 'b', 'c', 'd']
 
# printing initial json
print("initial 1st dictionary", ini_dict)
 
# changing keys of dictionary
final_dict = dict(zip(ini_list, list(ini_dict.values())))
 
# printing final result
print("final dictionary", str(final_dict))


Output

initial 1st dictionary {'nikhil': 1, 'vashu': 5, 'manjeet': 10, 'akshat': 15}
final dictionary {'a': 1, 'b': 5, 'c': 10, 'd': 15}

Creating a new dictionary and deleting the old one:

Approach:

Create a new empty dictionary new_dict.
Loop through each key-value pair in the original dictionary using the items() method.
If the current key is “Amit”, add a new key-value pair to new_dict with the key “Suraj” and the value from the original dictionary.
If the current key is not “Amit”, add the key-value pair from the original dictionary to new_dict.
Delete the old dictionary and rename new_dict to the original dictionary’s name.

Python3




my_dict = {'nikhil': 1, 'manjeet': 10, 'Amit': 15}
new_dict = {}
for key, value in my_dict.items():
    if key == 'Amit':
        new_dict['Suraj'] = value
    else:
        new_dict[key] = value
del my_dict
my_dict = new_dict
print(my_dict)


Output

{'nikhil': 1, 'manjeet': 10, 'Suraj': 15}

Time Complexity: O(n)
Auxiliary Space: O(n)



Previous Article
Next Article

Similar Reads

Different ways of sorting Dictionary by Keys and Reverse sorting by keys
Prerequisite: Dictionaries in Python A dictionary is a collection which is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. We can access the values of the dictionary using keys. In this article, we will discuss 10 different ways of sorting the Python dictionary by keys and a
8 min read
Python - Append Dictionary Keys and Values ( In order ) in dictionary
Given a dictionary, perform append of keys followed by values in list. Input : test_dict = {"Gfg" : 1, "is" : 2, "Best" : 3} Output : ['Gfg', 'is', 'Best', 1, 2, 3] Explanation : All the keys before all the values in list. Input : test_dict = {"Gfg" : 1, "Best" : 3} Output : ['Gfg', 'Best', 1, 3] Explanation : All the keys before all the values in
5 min read
Python Program to create a sub-dictionary containing all keys from dictionary list
Given the dictionary list, our task is to create a new dictionary list that contains all the keys, if not, then assign None to the key and persist of each dictionary. Example: Input : test_list = [{'gfg' : 3, 'is' : 7}, {'gfg' : 3, 'is' : 1, 'best' : 5}, {'gfg' : 8}]Output : [{'is': 7, 'best': None, 'gfg': 3}, {'is': 1, 'best': 5, 'gfg': 3}, {'is':
8 min read
Python - Change Keys Case in Dictionary
Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform manipulation of cases of keys. This can have possible application in many domains including school programming and data domains. Lets discuss a way to solve this task. Input : test_dict = {'Gfg' : {'a' : 5, 'b' : {'best' : 6}}} Output : {'GFG': {'A'
5 min read
Python - Extract selective keys' values Including Nested Keys
Sometimes, while working with Python dictionaries, we can have a problem in which we need to extract selective keys' values. This problem has been solved earlier, but sometimes, we can have multiple nestings and certain keys may be present in inner records. This problem caters all the nestings for extraction of keys' values. Let's discuss certain w
7 min read
Python | Split dictionary keys and values into separate lists
Given a dictionary, the task is to split a dictionary in python into keys and values into different lists. Let's discuss the different ways we can do this. Example Input: {'a': 'akshat', 'b': 'bhuvan', 'c': 'chandan'} Output: keys: ['a', 'b', 'c'] values: ['akshat', 'bhuvan', 'chandan']Method 1: Split dictionary keys and values using inbuilt functi
5 min read
Python - Filter immutable rows representing Dictionary Keys from Matrix
Given Matrix, extract all the rows which has elements which have all elements which can be represented as dictionary key, i.e immutable. Input : test_list = [[4, 5, [2, 3, 2]], ["gfg", 1, (4, 4)], [{5:4}, 3, "good"], [True, "best"]] Output : [['gfg', 1, (4, 4)], [True, 'best']] Explanation : All elements in tuples are immutable. Input : test_list =
7 min read
Python dictionary with keys having multiple inputs
Prerequisite: Python-Dictionary. How to create a dictionary where a key is formed using inputs? Let us consider an example where have an equation for three input variables, x, y, and z. We want to store values of equation for different input triplets. Example 1: C/C++ Code # Python code to demonstrate a dictionary # with multiple inputs in a key. i
4 min read
Python - Cumulative Mean of Dictionary keys
Given the dictionary list, our task is to write a Python Program to extract the mean of all keys. Input : test_list = [{'gfg' : 34, 'is' : 8, 'best' : 10}, {'gfg' : 1, 'for' : 10, 'geeks' : 9, 'and' : 5, 'best' : 12}, {'geeks' : 8, 'find' : 3, 'gfg' : 3, 'best' : 8}] Output : {'gfg': 12.666666666666666, 'is': 8, 'best': 10, 'for': 10, 'geeks': 8.5,
6 min read
Python Dictionary keys() method
The keys() method in Python Dictionary, returns a view object that displays a list of all the keys in the dictionary in order of insertion using Python. Syntax: dict.keys() Parameters: There are no parameters. Returns: A view object is returned that displays all the keys. This view object changes according to the changes in the dictionary. Method 1
2 min read
three90RightbarBannerImg