me45 me45 - 1 year ago 174
Python Question

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}

Answer Source
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()}


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download