Python Program to Swap dictionary item’s position
Last Updated :
04 May, 2023
Given a Dictionary, the task is to write a python program to swap positions of dictionary items. The code given below takes two indices and swap values at those indices.
Input : test_dict = {‘Gfg’ : 4, ‘is’ : 1, ‘best’ : 8, ‘for’ : 10, ‘geeks’ : 9}, i, j = 1, 3
Output : {‘Gfg’: 4, ‘for’: 10, ‘best’: 8, ‘is’: 1, ‘geeks’: 9}
Explanation : (for : 10) and (is : 1) swapped order.
Input : test_dict = {‘Gfg’ : 4, ‘is’ : 1, ‘best’ : 8, ‘for’ : 10, ‘geeks’ : 9}, i, j = 2, 3
Output : {‘Gfg’: 4, ‘is’: 1, ‘for’: 10, ‘best’: 8, ‘geeks’: 9}
Explanation : (for : 10) and (best : 8) swapped order.
Method : Using items() and dict()
This task is achieved in 3 steps:
- First dictionary is converted to equivalent key value pairs in form of tuples,
- Next swap operation is performed in a Pythonic way.
- At last, tuple list is converted back to dictionary, in its required format.
Example:
Python3
test_dict = { 'Gfg' : 4 , 'is' : 1 , 'best' : 8 , 'for' : 10 , 'geeks' : 9 }
print ( "The original dictionary is : " + str (test_dict))
i, j = 1 , 3
tups = list (test_dict.items())
tups[i], tups[j] = tups[j], tups[i]
res = dict (tups)
print ( "The swapped dictionary : " + str (res))
|
Output:
The original dictionary is : {‘Gfg’: 4, ‘is’: 1, ‘best’: 8, ‘for’: 10, ‘geeks’: 9}
The swapped dictionary : {‘Gfg’: 4, ‘for’: 10, ‘best’: 8, ‘is’: 1, ‘geeks’: 9}
Time Complexity: O(n)
Auxiliary Space: O(1)
Method 2 ; dictionary manipulation using built-in functions and data types.
Here are the steps:
Initialize a dictionary test_dict with some key-value pairs.
Print the original dictionary.
Initialize two variables i and j with the indices of the key-value pairs that need to be swapped.
Convert the dictionary to a list of tuples using the items() method.
Swap the tuples at indices i and j in the list using tuple unpacking.
Convert the list of tuples back to a dictionary using the dict() method.
Print the swapped dictionary.
Python3
test_dict = { 'Gfg' : 4 , 'is' : 1 , 'best' : 8 , 'for' : 10 , 'geeks' : 9 }
print ( "The original dictionary is : " + str (test_dict))
i, j = 1 , 3
tups = list (test_dict.items())
tups[i], tups[j] = tups[j], tups[i]
res = dict (tups)
print ( "The swapped dictionary : " + str (res))
|
Output
The original dictionary is : {'Gfg': 4, 'is': 1, 'best': 8, 'for': 10, 'geeks': 9}
The swapped dictionary : {'Gfg': 4, 'for': 10, 'best': 8, 'is': 1, 'geeks': 9}
The time complexity of this program is O(n), where n is the number of key-value pairs in the dictionary.
The space complexity of the program is O(n), as we are creating a new list of tuples to store the key-value pairs, and then creating a new dictionary from this list.
METHOD 3:Using loop
APPROACH:
The problem is to swap the positions of key-value pairs in a dictionary in Python using a loop.
ALGORITHM:
1.Create an empty dictionary swapped_dict to store the swapped key-value pairs.
2.Iterate over the key-value pairs of the original dictionary original_dict using a for loop.
3.For each key-value pair, swap the positions of the key and value and add them to the swapped_dict dictionary.
4.Print the swapped_dict dictionary.
Python3
original_dict = { 'Gfg' : 4 , 'is' : 1 , 'best' : 8 , 'for' : 10 , 'geeks' : 9 }
swapped_dict = {}
for key, value in original_dict.items():
swapped_dict[value] = key
print ( "The swapped dictionary :" , swapped_dict)
|
Output
The swapped dictionary : {4: 'Gfg', 1: 'is', 8: 'best', 10: 'for', 9: 'geeks'}
Time Complexity:
The time complexity of the algorithm is O(n), where n is the number of key-value pairs in the dictionary. This is because we need to iterate over each key-value pair once.
Space Complexity:
The space complexity of the algorithm is also O(n), where n is the number of key-value pairs in the dictionary. This is because we need to create an empty dictionary to store the swapped key-value pairs. The size of this dictionary will be the same as the original dictionary.
Similar Reads
How to Create a Dictionary in Python
The task of creating a dictionary in Python involves storing key-value pairs in a structured and efficient manner, enabling quick lookups and modifications. A dictionary is an unordered, mutable data structure where each key must be unique and immutable, while values can be of any data type. For exa
3 min read
Python - Add Dictionary Items
In Python, dictionaries are a built-in data structure that stores key-value pairs. Adding items to a dictionary is a common operation when you're working with dynamic data or building complex data structures. This article covers various methods for adding items to a dictionary in Python. Adding Item
4 min read
Python Add Dictionary Key
In Python, dictionaries are unordered collections of key-value pairs. Each item in a dictionary is accessed by its unique key, which allows for efficient storage and retrieval of data. While dictionaries are commonly used with existing keys, adding a new key is an essential operation when working wi
4 min read
Python Access Dictionary
In Python, dictionaries are powerful and flexible data structures used to store collections of data in key-value pairs. To get or "access" a value stored in a dictionary, we need to know the corresponding key. In this article, we will explore all the ways to access dictionary values, keys, and both
4 min read
Python Change Dictionary Item
A common task when working with dictionaries is updating or changing the values associated with specific keys. This article will explore various ways to change dictionary items in Python. 1. Changing a Dictionary Value Using KeyIn Python, dictionaries allow us to modify the value of an existing key.
3 min read
Python Remove Dictionary Item
Sometimes, we may need to remove a specific item from a dictionary to update its structure. For example, consider the dictionary d = {'x': 100, 'y': 200, 'z': 300}. If we want to remove the item associated with the key 'y', several methods can help achieve this. Letâs explore these methods. Using po
3 min read
Get length of dictionary in Python
Python provides multiple methods to get the length, and we can apply these methods to both simple and nested dictionaries. Letâs explore the various methods. Using Len() FunctionTo calculate the length of a dictionary, we can use Python built-in len() method. It method returns the number of keys in
3 min read
Python - Value length dictionary
Sometimes, while working with a Python dictionary, we can have problems in which we need to map the value of the dictionary to its length. This kind of application can come in many domains including web development and day-day programming. Let us discuss certain ways in which this task can be perfor
4 min read
Python - Dictionary values String Length Summation
Sometimes, while working with Python dictionaries we can have problem in which we need to perform the summation of all the string lengths which as present as dictionary values. This can have application in many domains such as web development and day-day programming. Lets discuss certain ways in whi
4 min read
Calculating the Product of List Lengths in a Dictionary - Python
The task of calculating the product of the lengths of lists in a dictionary involves iterating over the dictionaryâs values, which are lists and determining the length of each list. These lengths are then multiplied together to get a single result. For example, if d = {'A': [1, 2, 3], 'B': [4, 5], '
3 min read