Search code examples
pythondictionarykey

switching keys and values in a dictionary in python


Say I have a dictionary like so:

my_dict = {2:3, 5:6, 8:9}

Is there a way that I can switch the keys and values to get:

{3:2, 6:5, 9:8}

Solution

  • For Python 3:

    my_dict2 = {y: x for x, y in my_dict.items()}
    

    For Python 2, you can use

    my_dict2 = dict((y, x) for x, y in my_dict.iteritems())