Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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} 
like image 857
me45 Avatar asked Nov 29 '11 03:11

me45


People also ask

Can Python dictionary have duplicate values with different keys?

The straight answer is NO. You can not have duplicate keys in a dictionary in Python.

Can dictionary have duplicate key values?

The Key value of a Dictionary is unique and doesn't let you add a duplicate key entry.


1 Answers

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

like image 86
GWW Avatar answered Sep 20 '22 15:09

GWW