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, "geeks": 10}, i, j = 1, 4
Output : {'Gfg': 2, 'is': 10, 'best': 7, 'for': 9, 'geeks': 4}
Explanation : Values of "is" and "geeks" swapped.
Input : test_dict = {"Gfg": 2, "is": 4, "best": 7, "for": 9, "geeks": 10}, i, j = 1, 2
Output : {'Gfg': 2, 'is': 7, 'best': 4, 'for': 9, 'geeks': 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
test_dict = { "Gfg" : 2 , "is" : 4 , "best" : 7 ,
"for" : 9 , "geeks" : 10 }
print ( "The original dictionary is : " + str (test_dict))
i, j = 1 , 3
vals = list (test_dict.values())
vals[i], vals[j] = vals[j], vals[i]
res = dict ()
for idx, key in enumerate (test_dict):
res[key] = vals[idx]
print ( "Required dictionary : " + str (res))
|
Output:
The original dictionary is : {‘Gfg’: 2, ‘is’: 4, ‘best’: 7, ‘for’: 9, ‘geeks’: 10} Required dictionary : {‘Gfg’: 2, ‘is’: 9, ‘best’: 7, ‘for’: 4, ‘geeks’: 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
test_dict = { "Gfg" : 2 , "is" : 4 , "best" : 7 ,
"for" : 9 , "geeks" : 10 }
print ( "The original dictionary is : " + str (test_dict))
i, j = 1 , 3
vals = list (test_dict.values())
vals[i], vals[j] = vals[j], vals[i]
res = {key: vals[idx] for idx, key in enumerate (test_dict)}
print ( "Required dictionary : " + str (res))
|
Output
The original dictionary is : {'Gfg': 2, 'is': 4, 'best': 7, 'for': 9, 'geeks': 10}
Required dictionary : {'Gfg': 2, 'is': 9, 'best': 7, 'for': 4, 'geeks': 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
test_dict = { "Gfg" : 2 , "is" : 4 , "best" : 7 ,
"for" : 9 , "geeks" : 10 }
print ( "The original dictionary is : " + str (test_dict))
i, j = 1 , 3
items = list (test_dict.items())
items[i], items[j] = items[j], items[i]
res = dict (items)
print ( "Required dictionary : " + str (res))
|
Output
The original dictionary is : {'Gfg': 2, 'is': 4, 'best': 7, 'for': 9, 'geeks': 10}
Required dictionary : {'Gfg': 2, 'for': 9, 'best': 7, 'is': 4, 'geeks': 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
test_dict = { "Gfg" : 2 , "is" : 4 , "best" : 7 , "for" : 9 , "geeks" : 10 }
print ( "The original dictionary is : " + str (test_dict))
i, j = 1 , 3
keys_list = list (test_dict.keys())
val_i = test_dict.pop(keys_list[i])
val_j = test_dict.pop(keys_list[j])
test_dict.update({keys_list[i]: val_j, keys_list[j]: val_i})
print ( "Required dictionary : " + str (test_dict))
|
Output
The original dictionary is : {'Gfg': 2, 'is': 4, 'best': 7, 'for': 9, 'geeks': 10}
Required dictionary : {'Gfg': 2, 'best': 7, 'geeks': 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
test_dict = { "Gfg" : 2 , "is" : 4 , "best" : 7 ,
"for" : 9 , "geeks" : 10 }
print ( "The original dictionary is : " + str (test_dict))
i, j = 1 , 3
temp = 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
print ( "Required dictionary : " + str (test_dict))
|
Output
The original dictionary is : {'Gfg': 2, 'is': 4, 'best': 7, 'for': 9, 'geeks': 10}
Required dictionary : {'Gfg': 2, 'is': 9, 'best': 7, 'for': 4, 'geeks': 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.
Last Updated :
12 Apr, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...