Showing posts with label swap. Show all posts
Showing posts with label swap. Show all posts

Thursday, April 1, 2010

Python: Swapping the keys and values of a dictionary

A function to swap the keys and immutable values of a dictionary.
def swap_dict(a_dict):
    return {val:key for key, val in a_dict.items()}
Example of usage:
>>> print(swap_dict({1: 'a', 2: 'b', 3: 'c'}))
{'a': 1, 'c': 3, 'b': 2}