Python – Swap ith and jth key’s value in dictionary

Given a dictionary, perform swapping of ith and jth index key’s value.
Input : test_dict = {"Gfg": 2, "is": 4, "best": 7, "for": 9, "zambiatek": 10}, i, j = 1, 4
Output : {'Gfg': 2, 'is': 10, 'best': 7, 'for': 9, 'zambiatek': 4}
Explanation : Values of "is" and "zambiatek" swapped.
Input : test_dict = {"Gfg": 2, "is": 4, "best": 7, "for": 9, "zambiatek": 10}, i, j = 1, 2
Output : {'Gfg': 2, 'is': 7, 'best': 4, 'for': 9, 'zambiatek': 10}
Explanation : Values of "is" and "best" swapped.
Method #1 : Using loop + values()
This is one of the ways in which this task can be performed. In this, we get the required swap key’s values and perform the required swap in loop, which creates a new dictionary.
Python3
# Python3 code to demonstrate working of# Swap ith and jth key's value in dictionary# Using loop + values()# initializing dictionarytest_dict = {"Gfg": 2, "is": 4, "best": 7, "for": 9, "zambiatek": 10}# printing original dictionaryprint("The original dictionary is : " + str(test_dict))# initializing i, ji, j = 1, 3# Extracting keysvals = list(test_dict.values())# performing swapvals[i], vals[j] = vals[j], vals[i]# setting new valuesres = dict()for idx, key in enumerate(test_dict): res[key] = vals[idx]# printing resultprint("Required dictionary : " + str(res)) |
Output:
The original dictionary is : {‘Gfg’: 2, ‘is’: 4, ‘best’: 7, ‘for’: 9, ‘zambiatek’: 10} Required dictionary : {‘Gfg’: 2, ‘is’: 9, ‘best’: 7, ‘for’: 4, ‘zambiatek’: 10}
Method #2 : Using values() + dictionary comprehension
This is one of the ways in which this task can be performed. This is a method similar to the above, the difference being that the dictionary assigning step is performed using dictionary comprehension.
Python3
# Python3 code to demonstrate working of# Swap ith and jth key's value in dictionary# Using values() + dictionary comprehension# initializing dictionarytest_dict = {"Gfg": 2, "is": 4, "best": 7, "for": 9, "zambiatek": 10}# printing original dictionaryprint("The original dictionary is : " + str(test_dict))# initializing i, ji, j = 1, 3# Extracting keysvals = list(test_dict.values())# performing swapvals[i], vals[j] = vals[j], vals[i]# setting new valuesres = {key: vals[idx] for idx, key in enumerate(test_dict)}# printing resultprint("Required dictionary : " + str(res)) |
The original dictionary is : {'Gfg': 2, 'is': 4, 'best': 7, 'for': 9, 'zambiatek': 10}
Required dictionary : {'Gfg': 2, 'is': 9, 'best': 7, 'for': 4, 'zambiatek': 10}
Method #3: Using items() + dict() constructor
Step-by-step approach:
- Initialize the dictionary and the values of i and j.
- Create a list of items from the dictionary using the items() method.
- Swap the values of the ith and jth items using tuple unpacking and indexing.
- Convert the list of items back into a dictionary using the dict() constructor.
- Print the original and modified dictionaries.
Below is the implementation of the above approach:
Python3
# Python3 code to demonstrate working of# Swap ith and jth key's value in dictionary# Using items() + dict() constructor# initializing dictionarytest_dict = {"Gfg": 2, "is": 4, "best": 7, "for": 9, "zambiatek": 10}# printing original dictionaryprint("The original dictionary is : " + str(test_dict))# initializing i, ji, j = 1, 3# convert dictionary to a list of (key, value) tuplesitems = list(test_dict.items())# swap values of ith and jth itemsitems[i], items[j] = items[j], items[i]# create a new dictionary from the modified list of itemsres = dict(items)# printing resultprint("Required dictionary : " + str(res)) |
The original dictionary is : {'Gfg': 2, 'is': 4, 'best': 7, 'for': 9, 'zambiatek': 10}
Required dictionary : {'Gfg': 2, 'for': 9, 'best': 7, 'is': 4, 'zambiatek': 10}
Time complexity: O(n), Where n is the number of key-value pairs in the dictionary. Converting the dictionary to a list of tuples takes O(n) time, and swapping two elements in a list takes constant time.
Auxiliary space: O(n), For creating a new list of tuples and a new dictionary.
Method #4: Using pop() and update()
Step-by-step approach:
- Initialize the dictionary.
- Initialize the values of i and j.
- Get the i-th and j-th keys using the keys() method and convert them to a list.
- Get the values of i-th and j-th keys using the pop() method.
- Swap the values of i-th and j-th keys.
- Update the dictionary with the new values using the update() method.
- Print the modified dictionary.
Below is the implementation of the above approach:
Python3
# Python3 code to demonstrate working of# Swap ith and jth key's value in dictionary# Using pop() and update() method# initializing dictionarytest_dict = {"Gfg": 2, "is": 4, "best": 7, "for": 9, "zambiatek": 10}# printing original dictionaryprint("The original dictionary is : " + str(test_dict))# initializing i, ji, j = 1, 3# Extracting keyskeys_list = list(test_dict.keys())# getting the values of i-th and j-th keysval_i = test_dict.pop(keys_list[i])val_j = test_dict.pop(keys_list[j])# performing swaptest_dict.update({keys_list[i]: val_j, keys_list[j]: val_i})# printing resultprint("Required dictionary : " + str(test_dict)) |
The original dictionary is : {'Gfg': 2, 'is': 4, 'best': 7, 'for': 9, 'zambiatek': 10}
Required dictionary : {'Gfg': 2, 'best': 7, 'zambiatek': 10, 'is': 9, 'for': 4}
Time complexity: O(n), where n is the number of keys in the dictionary
Auxiliary space: O(1), as we are not using any extra space in the algorithm.
Method #5 : Using a temporary variable
- Initialize a dictionary named “test_dict” with key-value pairs.
- Print the original dictionary using the print() function and concatenation with the str() function.
- Initialize two variables i and j with the values 1 and 3, respectively. These variables represent the indices of the keys in the dictionary whose values will be swapped.
- Create a temporary variable named “temp” to store the value of the i-th key in the dictionary.
Swap the values of the i-th and j-th keys in the dictionary using the temporary variable. - Print the modified dictionary using the print() function and concatenation with the str() function.
Python3
# initializing dictionarytest_dict = {"Gfg": 2, "is": 4, "best": 7, "for": 9, "zambiatek": 10}# printing original dictionaryprint("The original dictionary is : " + str(test_dict))# initializing i, ji, j = 1, 3# swapping values using a temporary variabletemp = test_dict[list(test_dict.keys())[i]]test_dict[list(test_dict.keys())[i]] = test_dict[list(test_dict.keys())[j]]test_dict[list(test_dict.keys())[j]] = temp# printing resultprint("Required dictionary : " + str(test_dict)) |
The original dictionary is : {'Gfg': 2, 'is': 4, 'best': 7, 'for': 9, 'zambiatek': 10}
Required dictionary : {'Gfg': 2, 'is': 9, 'best': 7, 'for': 4, 'zambiatek': 10}
Time complexity of O(n), where n is the size of the dictionary.
Auxiliary space of O(1) since we only use a single temporary variable.



