Open In App

Python Program to Swap dictionary item’s position

Last Updated : 04 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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




# initializing dictionary
test_dict = {'Gfg': 4, 'is': 1, 'best': 8, 'for': 10, 'geeks': 9}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing swap indices
i, j = 1, 3
 
# conversion to tuples
tups = list(test_dict.items())
 
# swapping by indices
tups[i], tups[j] = tups[j], tups[i]
 
# converting back
res = dict(tups)
 
# printing result
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




# initializing dictionary
test_dict = {'Gfg': 4, 'is': 1, 'best': 8, 'for': 10, 'geeks': 9}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing swap indices
i, j = 1, 3
 
# conversion to tuples
tups = list(test_dict.items())
 
# swapping by indices
tups[i], tups[j] = tups[j], tups[i]
 
# converting back to dictionary
res = dict(tups)
 
# printing result
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 dictionary
original_dict = {'Gfg': 4, 'is': 1, 'best': 8, 'for': 10, 'geeks': 9}
 
# Create an empty dictionary to store the swapped items
swapped_dict = {}
 
# Swap the positions of items using a loop
for key, value in original_dict.items():
    swapped_dict[value] = key
 
# Print the swapped dictionary
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.



Previous Article
Next Article

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): One naive solution maybe something like just swa
4 min read
Python | Remove item from dictionary when key is unknown
Dictionary is a collection which is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. It is widely used in day to day programming, web development, and machine learning. Let's discuss the various ways to remove items from the dictionary when key is unknown. Method #1 : Using n
6 min read
Python - Add item after given Key in dictionary
Given a dictionary and a Key, add new item after a particular key in dictionary. Input : test_dict = {"Gfg" : 3, "is" : 5, "for" : 8, "Geeks" : 10}, K = "is", add_item = {"good" : 19} Output : {'Gfg': 3, 'is': 5, 'good': 19, 'for': 8, 'Geeks': 10} Explanation : Item added after desired key in dictionary. Input : test_dict = {"Gfg" : 3, "is" : 5, "f
4 min read
Python Remove Item from Dictionary by Value
Python, with its elegant syntax and powerful data structures, stands out as one of the most favored programming languages. Among its arsenal of data structures, the dictionary is a versatile and indispensable tool for developers. Dictionaries facilitate the storage of key-value pairs, allowing for efficient data retrieval and manipulation. In this
3 min read
Python Remove Item from Dictionary by Key
A dictionary in Python is a mutable and dynamic data type that provides a flexible way to access and manipulate data. As distinct from a list or a tuple, where elements are accessed via indices, a dictionary leverages a unique key representing each item. In this article, we will see how to remove items from the dictionary by key in Python. Remove I
3 min read
Delete a Python Dictionary Item If the Key Exists
In Python, dictionaries are like containers that help us keep and find information easily. They use key-value pairs to organize data, making them super helpful. But sometimes, we need to get rid of something specific from the dictionary, like when we know the key. This article explores some simple ways to do that efficiently How To Delete A Diction
3 min read
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
6 min read
Python program to update a dictionary with the values from a dictionary list
Given a dictionary and dictionary list, update the dictionary with dictionary list values. Input : test_dict = {"Gfg" : 2, "is" : 1, "Best" : 3}, dict_list = [{'for' : 3, 'all' : 7}, {'and' : 1, 'CS' : 9}] Output : {'Gfg': 2, 'is': 1, 'Best': 3, 'for': 3, 'all': 7, 'and': 1, 'CS': 9} Explanation : All dictionary keys updated in single dictionary. I
8 min read
Python Program to create a sub-dictionary containing all keys from dictionary list
Given the dictionary list, our task is to create a new dictionary list that contains all the keys, if not, then assign None to the key and persist of each dictionary. Example: Input : test_list = [{'gfg' : 3, 'is' : 7}, {'gfg' : 3, 'is' : 1, 'best' : 5}, {'gfg' : 8}]Output : [{'is': 7, 'best': None, 'gfg': 3}, {'is': 1, 'best': 5, 'gfg': 3}, {'is':
8 min read
Python - Count if dictionary position equals key or value
Given a dictionary, count instances where dictionary item position equals key or value. Valid for Py >= 3.6 [ Introduction of dictionary ordering ]. Input : test_dict = {5:3, 2:3, 10:4, 7:3, 8:1, 9:5} Output : 2 Explanation : At 3 and 5th position, values are 3 and 5. Input : test_dict = {5:3, 2:3, 10:4, 8:1, 9:5} Output : 1 Explanation : At 5th
3 min read
Practice Tags :
three90RightbarBannerImg