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

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

If you are using python 2.7 or 3.x you can use a dictionary comprehension instead:

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

Edit

As noted in the comments by JBernardo, for python 3.x you need to use items instead of iteritems


my_dict = { my_dict[k]:k for k in my_dict}

Try this:

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

new_dict = {}
for k, v in my_dict.items():
    new_dict[v] = k

Use this code (trivially modified) from the accepted answer at Python reverse / invert a mapping:

dict((v,k) for k, v in my_dict.iteritems())

Note that this assumes that the values in the original dictionary are unique. Otherwise you'd end up with duplicate keys in the resulting dictionary, and that is not allowed.

And, as @wim points out, it also assumes the values are hashable. See the Python glossary if you're not sure what is and isn't hashable.