switching keys and values in a dictionary in python [duplicate]

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())

Leave a Comment