Python program to Swap Keys and Values in Dictionary


Dictionaries are a fundamental data structure in Python, providing a way to store key-value pairs. They offer quick and efficient access to values based on their associated keys. However, there may be scenarios where you need to reverse the roles of keys and values in a dictionary. This is where the concept of swapping keys and values becomes valuable.

In this article, we will explore a Python program that swaps the keys and values in a dictionary. We will delve into the step-by-step approach and provide a detailed implementation of the program. Along the way, we will discuss potential use cases and highlight the benefits of performing such an operation.

So, whether you're working on data manipulation, data transformations, or simply exploring new programming techniques, understanding how to swap keys and values in a dictionary will broaden your Python programming capabilities.

Understanding the Problem

Before we dive into the implementation details, let's take a moment to understand the problem of swapping keys and values in a dictionary. In Python, dictionaries are unordered collections of key-value pairs, where each key is unique. They provide an efficient way to retrieve values based on their associated keys.

However, there are situations where you may need to reverse the roles of keys and values in a dictionary. This can be useful in various scenarios, such as −

  • Data Restructuring  When you have a dictionary where the keys represent categories or labels, and the values represent corresponding data points, swapping the keys and values can be beneficial for restructuring the data.

  • Unique Value Mapping  If the original dictionary has unique values, swapping the keys and values can create a new dictionary where the values become keys and the original keys become values. This can be useful for performing value-based lookups or creating a mapping of unique values to their corresponding keys.

  • Removing Duplicates  Swapping keys and values can help identify and eliminate duplicate values in a dictionary. By swapping the keys and values, duplicate values will become keys, and you can remove the duplicates by considering only the unique keys.

By understanding the problem and the potential use cases, we can now explore the approach and algorithm for swapping keys and values in a dictionary.

Approach and Algorithm

To swap keys and values in a dictionary, we can follow a straightforward approach that involves iterating over the original dictionary and creating a new dictionary where the keys are the original values, and the values are the original keys. Here's a step-by-step procedure to accomplish this task 

  • Create an empty dictionary to store the swapped key-value pairs.

  • Iterate over the items of the original dictionary using a loop.

  • For each key-value pair in the original dictionary, assign the key as the value and the value as the key in the new dictionary.

  • Repeat this process for all items in the original dictionary.

  • After iterating through all the items, the new dictionary will contain the swapped key-value pairs.

  • Return the new dictionary as the output.

By following this approach, we can efficiently swap the keys and values in a dictionary and obtain a new dictionary with the reversed associations.

Implementation

Now that we understand the approach and algorithm, let's dive into the implementation of the Python program to swap keys and values in a dictionary. Here's the code 

def swap_keys_values(dictionary):
    swapped_dict = {value: key for key, value in dictionary.items()}
    return swapped_dict

In the above code, we define a function swap_keys_values that takes a dictionary as input and returns a new dictionary with the swapped key-value pairs. Here's how the implementation works 

  • We create an empty dictionary called swapped_dict to store the swapped key-value pairs.

  • We use a dictionary comprehension to iterate over the items of the original dictionary using the items() method. For each key-value pair, we assign the value as the key and the key as the value in the new dictionary.

  • After iterating through all the items, we have successfully swapped the keys and values in the swapped_dict.

  • Finally, we return the swapped_dict as the output.

The implementation leverages the concise and powerful syntax of dictionary comprehensions in Python, making it efficient and elegant.

In the next section, we will test the program with some sample inputs and examine the expected output.

Example

my_dict = {'a': 1, 'b': 2, 'c': 3}
print(swap_keys_values(my_dict))

Output

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

Example

my_dict = {'apple': 'fruit', 'carrot': 'vegetable', 'banana': 'fruit'}
print(swap_keys_values(my_dict))

Output

{'fruit': 'apple', 'vegetable': 'carrot'}

Example

my_dict = {1: 'one', 2: 'two', 3: 'three'}
print(swap_keys_values(my_dict))

Output

{'one': 1, 'two': 2, 'three': 3}

In each test case, we pass a dictionary as input to the swap_keys_values function and print the result. The expected output demonstrates the dictionary with the swapped key-value pairs.

Conclusion

In this article, we explored a Python program to swap keys and values in a dictionary. We discussed the approach and algorithm, provided a step-by-step procedure, and presented an implementation using dictionary comprehensions.

We started by understanding the problem and identifying the need to swap the keys and values in a dictionary. We then outlined an approach that involved iterating over the dictionary and creating a new dictionary with the reversed associations.

With the approach in mind, we delved into the implementation, where we defined a function swap_keys_values that utilized dictionary comprehensions to swap the keys and values. We provided a detailed explanation of the code and discussed how it achieved the desired outcome.

To validate the program's functionality, we conducted several test cases, which confirmed that the program successfully swapped the keys and values in the dictionary.

Updated on: 10-Aug-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements