Swapping Dictionary Values in Python

Swapping dictionary values in Python uses the age-old swap logic found in the course materials of many a computer science course. However, Python provides a simplified syntax for achieving such operations that can also be applied to dictionary objects!
python swap dictionary values alpharithms

Python dictionary objects are convenient means of storing key-value pairs. Dicts provide convenience methods for data access but leave developers to their own means for operations. For example, to swap the position of two values in a python dictionary one must devise a custom approach — there is no ‘swap’ method.

This is no difficult task and can be approached like any other basic swap logic implemented across many languages. Python does, however, provide does allow one to simplify the syntax of swaps — including among values in dict objects. This quick tutorial will look at several approaches and use-cases for swapping values in a Python dict.

TL;DR

Python’s evaluation order allows simplified syntax for making swaps. Dictionary items can have values swapped using the same syntax, such that the keys are conceptually like variables. This example code provides a demonstration:

# define key value pairs
d = {"a": 1, "b": 2, "c": 3}

# swap values using Pythonic syntax
d["a"], d["b"] = d["b"], d["a"]

# result
{'a': 2, 'b': 1, 'c': 3}

Quick Intro: Swapping Basics

Swapping is a foundational concept in computer science. How one chooses to exchange the value assigned to one variable with that assigned to a second is a logical sequence approached by many programs. It’s easy — but can cause those new to programming some confusion initially. Consider the following scenario:

# The first variable
variable_one = 1

# The second variable
variable_two = 2

Here we have two variables; variable_one and variable_two. Each has a unique integer value assigned. Our intention is to change them such that variable_1 has a resulting value of 2 and variable_2 has a resulting value of 1. We can easily assign the value of variable_2 to variable_1 but that’s where the trouble begins. Consider the following:

# swap first value
variable_1 = variable_2

# swap second value
variable_2 = variable_1 # <--------- keeps the same value!

When making the second swap — assigning the value of variable_1 to variable_2, there is no change because the value of variable_2 had just been assigned to variable_1. The second part of this code is equivalent of saying variable_2 = variable_2. Clearly, this isn’t “swapping” anything! The solution is to use a temporary value as such:

# 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   # <------- swap works here

In this approach, a copy of variable_1 is made before it is reassigned to another value. This provides the means of accessing that initial value after-the-fact such that our next assignment works as intended. This is a fundamental logical concept in computer science and programming. Let’s consider how to apply this to the swapping of two dict values in Python.

Swap Two Dict Values

Here we apply the swapping approach of using a temporary value to swap the value of two entries in a Python dict object. Consider the following code:

# define key value pairs
dict_items = {"a": 1, "b": 2, "c": 3}

# swap values of a and b
tmp = dict_items["a"]

# Make first swap
dict_items["a"] = dict_items["b"]

# Make second, using tmp value
dict_items["b"] = tmp

# View output
print(dict_items)

{'a': 2, 'b': 1, 'c': 3}

As expected, applying the same method of using a temporary value makes this swap procedure go off without a hitch. Python is designed in such a way that the evaluation order of expressions allows us to simplify these operations.

Python-Specific Swapping

Python’s evaluation order defines the order in which expressions and assignment statements are interpreted. Before we dive into how swapping in Python works, let’s see the syntax in action:

# Define two variables
variable_1 = 1
variable_2 = 2

# swap values Pythonically
variable_1, variable_2 = variable_2, variable_1

# View result
print("variable_1:", variable_1)
print("variable_2:", variable_2)

variable_1: 2
variable_2: 1

Here the values of variable_1 and variable_2 are swapped without using a temporary variable! But, how can that be? Under the hood, Python’s evaluation order does something similar to the following:

  1. Evaluates the right-hand side (RHS) of the expression, creating a tuple of two elements in memory for the values of variable_1 and variable_2.
  2. Evaluates the left-hand side (LHS) of the expression, assigning the tuple of values stored in memory, with associated names, the names on the LHS.
  3. Unpacks the tuple in memory such that the first argument of the LHS (variable_1) is assigned to the first value on the RHS (variable_2).

It is important to note that “under-the-hood” Python is using the same concept of temporary variables as we’ve been using to this point. This “syntactic sugar” merely makes the programming experience simpler. There is no avoiding the logical requirements on an absolute level. Wiht this method in mind, let us now consider how to swap two dictionary values in Python again.

Swap Two Dict Values Pythonically

Again, we have a dictionary object with several key-value pairs. Again, our intention is to exchange the values assigned to two keys such that they are effectively “swapped” upon completion. Consider the following example code:

# 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)
Result: {'a': 2, 'b': 1, 'c': 3}

Here we see the Pythonic way of swapping works within the confines of a dict object just as it does with non-dict variable objects. This is effective for swapping the values of two dict items but what if we wanted to swap the position of two items in a Python dictionary? For that, we need to incorporate some additional logic!

Swap Position of Two Items in a Python Dict

Up until this point, we have been swapping the values of variables. In the case of swapping the values of two dictionary key entries, the same concept holds: we have two variables (dict items in this case) to which we are performing an assignment operation.

To swap the actual order of two items in a dictionary, we are still performing an assignment operation but, in this case, the “assignment” is the index order of the dictionary. The issue here is that dictionary objects do not have an indexed order. 

To “swap” the position of two dict items we must first convert the dict object to an orderable object, like a list or tuple. Given dict objects have key-value pairs, a tuple object fits perfectly. Consider the following approach:

# 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)

Result: {'b': 2, 'a': 1, 'c': 3}

Here we see a conversion of the non-indexed dict object d into an indexed list object of tuple pairs t such that the “swap” is between index values. This swap happens with the same assignment order expression syntax, just outside of the dict object. Then, the correctly swapped values are converted back into a dict object.

Disclaimer

This approach is interesting but not optimal. If the order of values in a dict object needs to be altered there is a strong chance that another data structure like a list or tuple is a better choice to hold references to data. There are plenty of data structures out there, each better suited to certain situations.

Final Thoughts

Python allows the swapping of data to be approached with a minimized syntax compared to other languages. We’ve shown how to swap two values throughout this article, but the syntax extends to as many arguments as one should desire. For example, a, b, c, d, e = d, c, e, b, a is completely value syntax.

Python’s dict objects are incredibly powerful tools when applied appropriately but, as with other hash table-esque data structures, not ideal for storing data such that order is important (or predictable!) Nevertheless, performing actions like swaps or even sorting a Python dictionary is possible and, in the right circumstance, possibly appropriate.

Zαck West
Full-Stack Software Engineer with 10+ years of experience. Expertise in developing distributed systems, implementing object-oriented models with a focus on semantic clarity, driving development with TDD, enhancing interfaces through thoughtful visual design, and developing deep learning agents.