Swap Position Of Two Values Python Dictionary

Swap Position Of Two Values Python Dictionary is done with the same swap logic that is taught in many computer science classes. But Python offers a simpler way to do these things that can also be used with dictionary objects.

Dictionary is a very useful data structure in programming. It is usually used to hash a key and its value together so that they can be found quickly.

Swap Position Of Two Values Python Dictionary
Swap Position Of Two Values Python Dictionary

Swapping Basics

Swapping is a basic concept in computer science. Many programs use a logical sequence to decide how to switch the value of one variable with the value of another.

It’s easy, but people who are new to programming may be confused at first. Consider the following situation:

# The first variable
variable_one = 1
# The second variable
variable_two = 2

We have two variables here: variable_one and variable_two. Each one has its own unique integer value. Our goal is to change them so that the final value of variable_1 is 2 and the final value of variable_2 is 1. We can easily give variable 2’s value to variable_1, but that’s where the problems start. Think about these things:

# swap first value
variable_1 = variable_2
# swap second value
variable_2 = variable_1

The second swap, which involves giving the value of variable_1 to variable_2, doesn’t change anything because the value of variable_2 had just been given to variable_1.

This code’s second part is the same as saying variable_2 = variable_2. Clearly, nothing is being “swapped” here! The answer is to use a temporary value like this:

# create a temporary value
tmp = variable_1
# make first swap in same fashion
variable_1 = variable_2
# make second swap, using tmp value
variable_2 = tmp

In this method, variable_1 is copied before it is set to a different value. This gives us a way to find out what the initial value was after the fact, so that our next assignment works the way it should.

Swap of Key and Value in Python

1. Does not work when there are multiple same values.

One simple solution could be to switch the keys and values.

Example:

# Python3 code to demonstrate 
# swap of key and value
   
# initializing dictionary
old_dict = {'A': 10, 'B': 50, 'C': 70, 'D': 40, 'E': 20, 'F': 60, 'G': 50, 'H':20}
 
new_dict = dict([(value, key) for key, value in old_dict.items()])
   
# Printing original dictionary
print ("Original dictionary is : ")
print(old_dict)
 
print()
 
# Printing new dictionary after swapping keys and values
print ("Dictionary after swapping is :  ")
print("keys: values")
for i in new_dict:
    print(i, " :  ", new_dict[i])

Output:

Original dictionary is :
{‘A’: 10, ‘B’: 50, ‘C’: 70, ‘D’: 40, ‘E’: 20, ‘F’: 60, ‘G’: 50, ‘H’: 20}Dictionary after swapping is :

keys: values
10 : A
50 : G
70 : C
40 : D
20 : H
60 : F

But there is something wrong with this plan. In our example, we have several keys with the same value, like ('B', 50) and ('G', 50). ('E', 20) and ('H', 20) also have the same value.

But in the end, we only got one key from each of them. i.e., we only got ('G', 50) and ('E', 20). So, here’s another way to solve this problem:

2. Handles multiple same values

In this method, we’ll check to see if the value is already there. If it is already there, add it to the list.

Example:

# Python3 code to demonstrate 
# swap of key and value
   
# initializing dictionary
old_dict = {'A': 10, 'B': 50, 'C': 70, 'D': 40, 'E': 20, 'F': 60, 'G': 50, 'H':20}
 
# Printing original dictionary
print ("Original dictionary is : ")
print(old_dict)
 
print()
new_dict = {}
for key, value in old_dict.items():
   if value in new_dict:
       new_dict[value].append(key)
   else:
       new_dict[value]=[key]
 
# Printing new dictionary after swapping
# keys and values
print ("Dictionary after swapping is :  ")
print("keys: values")
for i in new_dict:
    print(i, " :", new_dict[i])

Output:

Original dictionary is :
{‘A’: 10, ‘B’: 50, ‘C’: 70, ‘D’: 40, ‘E’: 20, ‘F’: 60, ‘G’: 50, ‘H’: 20}

Dictionary after swapping is :
keys: values
10 : [‘A’]
50 : [‘B’, ‘G’]
70 : [‘C’]
40 : [‘D’]
20 : [‘E’, ‘H’]
60 : [‘F’]

Swap Two Dict Values Pythonically

We have a dictionary object with a number of pairs of keys and values. Our goal is to swap the values assigned to two keys so that they work as if they were “swapped” when the job is done. Look at the following code as an example:

Example:

# define key value pairs
d = {"a": 1, "b": 2, "c": 3}
# swap Pythonically
d["a"], d["b"] = d["b"], d["a"]
# view result
print("Result:", d)

Output:

Result: {‘a’: 2, ‘b’: 1, ‘c’: 3}

Here, we can see that the Pythonic way of swapping works inside a dict object just as well as it does inside variable objects that are not dicts.

This works well for swapping the values of two dict items, but what if we wanted to swap the order of two dict items? To do that, we need to add some more reasoning!

Swap Position of Two Items in a Python Dict

We’ve been swapping the values of variables up until now. The same idea applies to swapping the values of two dictionary key entries: we are doing an assignment operation on two variables (in this case, dict items).

To swap the actual order of two items in a dictionary, we still do an assignment operation, but this time the “assignment” is the index order of the dictionary. The problem is that dictionary objects don’t have an order that is based on an index.

To “swap” the order of two dict items, we must first turn the dict object into something that can be put in a certain order, like a list or tuple. Since dict objects have key-value pairs, a tuple object fits perfectly. Think about the following plan:

Example:

# define key value pairs
d = {"a": 1, "b": 2, "c": 3}
# convert to a tuple
t = list(d.items())
print("Tuples:", t)
Tuples: [('a', 1), ('b', 2), ('c', 3)]
# swap order via index values
t[0], t[1] = t[1], t[0]
print("Swapped:", t)
Swapped: [('b', 2), ('a', 1), ('c', 3)]
# Convert back to dictionary
d = dict(t)
print("Result:", d)

Output:

Tuples: [(‘a’, 1), (‘b’, 2), (‘c’, 3)]
Swapped: [(‘b’, 2), (‘a’, 1), (‘c’, 3)]
Result: {‘b’: 2, ‘a’: 1, ‘c’: 3}

Here, a non-indexed dict object called d is changed into an indexed list object of tuple pairs called t. The “swap” happens between the index values.

The same assignment order expression syntax is used for this swap, but it happens outside of the dict object. The values are then put back into a dict object after they have been swapped correctly.

Summary

In this tutorial we have discussed the Swap Position Of Two Values Python Dictionary in different examples, This tutorial provides example program with output that help your needs in Python Programming.

Leave a Comment