Open In App

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

Improve
Improve
Like Article
Like
Save
Share
Report

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




# Python3 code to demonstrate working of
# Swap ith and jth key's value in dictionary
# Using loop + values()
 
# initializing dictionary
test_dict = {"Gfg": 2, "is": 4, "best": 7,
             "for": 9, "geeks": 10}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing i, j
i, j = 1, 3
 
# Extracting keys
vals = list(test_dict.values())
 
# performing swap
vals[i], vals[j] = vals[j], vals[i]
 
# setting new values
res = dict()
for idx, key in enumerate(test_dict):
    res[key] = vals[idx]
 
# printing result
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




# Python3 code to demonstrate working of
# Swap ith and jth key's value in dictionary
# Using values() + dictionary comprehension
 
# initializing dictionary
test_dict = {"Gfg": 2, "is": 4, "best": 7,
             "for": 9, "geeks": 10}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing i, j
i, j = 1, 3
 
# Extracting keys
vals = list(test_dict.values())
 
# performing swap
vals[i], vals[j] = vals[j], vals[i]
 
# setting new values
res = {key: vals[idx] for idx, key in enumerate(test_dict)}
 
# printing result
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




# Python3 code to demonstrate working of
# Swap ith and jth key's value in dictionary
# Using items() + dict() constructor
 
# initializing dictionary
test_dict = {"Gfg": 2, "is": 4, "best": 7,
             "for": 9, "geeks": 10}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing i, j
i, j = 1, 3
 
# convert dictionary to a list of (key, value) tuples
items = list(test_dict.items())
 
# swap values of ith and jth items
items[i], items[j] = items[j], items[i]
 
# create a new dictionary from the modified list of items
res = dict(items)
 
# printing result
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




# Python3 code to demonstrate working of
# Swap ith and jth key's value in dictionary
# Using pop() and update() method
 
# initializing dictionary
test_dict = {"Gfg": 2, "is": 4, "best": 7, "for": 9, "geeks": 10}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing i, j
i, j = 1, 3
 
# Extracting keys
keys_list = list(test_dict.keys())
 
# getting the values of i-th and j-th keys
val_i = test_dict.pop(keys_list[i])
val_j = test_dict.pop(keys_list[j])
 
# performing swap
test_dict.update({keys_list[i]: val_j, keys_list[j]: val_i})
 
# printing result
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

  1. Initialize a dictionary named “test_dict” with key-value pairs.
  2. Print the original dictionary using the print() function and concatenation with the str() function.
  3. 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.
  4. 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.
  5. Print the modified dictionary using the print() function and concatenation with the str() function.

Python3




# initializing dictionary
test_dict = {"Gfg": 2, "is": 4, "best": 7,
             "for": 9, "geeks": 10}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing i, j
i, j = 1, 3
 
# swapping values using a temporary variable
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
 
# printing result
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
Previous
Next
Share your thoughts in the comments
Similar Reads