Python Dictionary – Swap Keys and Values

Python – Swap Dictionary Keys and Values

You can swap the dictionary keys and values in Python using Dictionary comprehension or a For loop.

In this tutorial, you will learn how to swap the keys and values in a dictionary, with examples.

1. Swapping dictionary keys and values using Dictionary Comprehension in Python

In the following program, you are given a dictionary my_dict with some initial key-value pairs. You have to swap the keys and values in the dictionary using Dictionary Comprehension.

Steps

  1. Given a dictionary in my_dict.
  2. Use dictionary comprehension, and for each key value in the original dictionary my_dict, swap the key value to value key and add it to the new dictionary.
  3. Store the returned dictionary in a variable, say swapped_dict. You may print the swapped dictionary to output using print() built-in function.

Program

Python Program

my_dict = {
    'foo':12,
    'bar':14
}

swapped_dict = {value: key for key, value in my_dict.items()}
print(swapped_dict)
Run Code Copy

Output

{12: 'foo', 14: 'bar'}

In the original dictionary my_dict, 'foo' and 'bar' are keys. But in the swapped dictionary 'foo' and 'bar' have become values and their values 12 and 14 have become keys.

2. Swapping dictionary keys and values using For loop in Python

In the following program, you are given a dictionary my_dict with some initial key-value pairs. You have to swap the keys and values in the dictionary using For loop.

Steps

  1. Given a dictionary in my_dict.
  2. Take an empty dictionary in swapped_dict.
  3. Use For loop to iterate over the items in the original dictionary my_dict.
    1. Inside the For loop, for each item in the original dictionary, add an item to the swapped_dict with key and value from the original dictionary swapped.
  4. After the completion of For loop, swapped_dict would contain the items from original dictionary my_dict with keys and values swapped.

Program

Python Program

my_dict = {
    'foo':12,
    'bar':14
}

swapped_dict = {}
for key, value in my_dict.items():
    swapped_dict[value] = key

print(swapped_dict)
Run Code Copy

Output

{12: 'foo', 14: 'bar'}

Summary

In this tutorial, we learned how to swap the keys and values in a dictionary using Dictionary Comprehension, or a For loop, with the help of well detailed Python programs.

Related Tutorials

Code copied to clipboard successfully 👍