Python - Swap ith and jth key's value in dictionary
Last Updated :
12 Apr, 2023
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))
OutputThe 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))
OutputThe 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))
OutputThe 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
# 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))
OutputThe 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.
Similar Reads
Python program to Swap Keys and Values in Dictionary
Dictionary is quite a useful data structure in programming that is usually used to hash a particular key with value so that they can be retrieved efficiently. Letâs discuss various ways of swapping the keys and values in Python Dictionary. Method#1 (Does not work when there are multiple same values
4 min read
Iterate Through Dictionary Keys And Values In Python
In Python, a Dictionary is a data structure where the data will be in the form of key and value pairs. So, to work with dictionaries we need to know how we can iterate through the keys and values. In this article, we will explore different approaches to iterate through keys and values in a Dictionar
2 min read
Python - Sort Dictionary List by Key's ith Index value
Given List of dictionaries, sort dictionaries on basis of Key's ith index value Input : [{"Gfg" : "Best", "for" : "Geeks"}, {"Gfg" : "Good", "for" : "Me"}, {"Gfg" : "Better", "for" : "All"}], K = "Gfg", i = 1 Output : [{'Gfg': 'Best', 'for': 'Geeks'}, {'Gfg': 'Better', 'for': 'All'}, {'Gfg': 'Good',
7 min read
Add Same Key in Python Dictionary
The task of adding the same key in a Python dictionary involves updating the value of an existing key rather than inserting a new key-value pair. Since dictionaries in Python do not allow duplicate keys, adding the same key results in updating the value of that key. For example, consider a dictionar
3 min read
Python Iterate Dictionary Key, Value
In Python, a Dictionary is a data structure that stores the data in the form of key-value pairs. It is a mutable (which means once created we modify or update its value later on) and unordered data structure in Python. There is a thing to keep in mind while creating a dictionary every key in the dic
3 min read
Python Dictionary Add Value to Existing Key
The task of adding a value to an existing key in a Python dictionary involves modifying the value associated with a key that is already present. Unlike adding new key-value pairs, this operation focuses on updating the value of an existing key, allowing us to increment, concatenate or otherwise adju
2 min read
Add a key value pair to Dictionary in Python
The task of adding a key-value pair to a dictionary in Python involves inserting new pairs or updating existing ones. This operation allows us to expand the dictionary by adding new entries or modify the value of an existing key.For example, starting with dictionary d = {'key1': 'geeks', 'key2': 'fo
3 min read
Initialize Python Dictionary with Keys and Values
In this article, we will explore various methods for initializing Python dictionaries with keys and values. Initializing a dictionary is a fundamental operation in Python, and understanding different approaches can enhance your coding efficiency. We will discuss common techniques used to initialize
3 min read
Python - Remove Dictionary if Given Key's Value is N
We are given a dictionary we need to remove key if the given value of key is N. For example, we are given a dictionary d = {'a': 1, 'b': 2, 'c': 3} we need to remove the key if the value is N so that the output becomes {'a': 1, 'c': 3}. We can use methods like del, pop and various other methods like
2 min read
Python - Sort Dictionary by Values and Keys
Given a dictionary, sort according to descended values, if similar values, then by keys lexicographically. Input : test_dict = {"gfg" : 1, "is" : 1, "best" : 1, "for" : 1, "geeks" : 1} Output : {"best" : 1, "is" : 1, "for" : 1, "geeks" : 1, "gfg" : 1} Explanation : All values are equal, hence lexico
3 min read