Swap Keys and Values in a Dictionary in Python

Modified: | Tags: Python, Dictionary

This article explains how to swap keys and values in a dictionary (dict) in Python.

Swap keys and values with dictionary comprehension and items()

You can swap keys and values in a dictionary with dictionary comprehensions and the items() method.

d = {'key1': 'val1', 'key2': 'val2', 'key3': 'val3'}

d_swap = {v: k for k, v in d.items()}
print(d_swap)
# {'val1': 'key1', 'val2': 'key2', 'val3': 'key3'}

Function implementation:

def get_swap_dict(d):
    return {v: k for k, v in d.items()}

d_swap = get_swap_dict(d)
print(d_swap)
# {'val1': 'key1', 'val2': 'key2', 'val3': 'key3'}

Note on dictionaries with duplicate values

In a dictionary, all keys must be unique, but values can be duplicated.

When swapping keys and values in a dictionary that contains duplicate values, only one instance of the duplicate value will be retained, since dictionary keys must be unique.

d_duplicate = {'key1': 'val1', 'key2': 'val1', 'key3': 'val3'}

d_duplicate_swap = get_swap_dict(d_duplicate)
print(d_duplicate_swap)
# {'val1': 'key2', 'val3': 'key3'}

Related Categories

Related Articles