Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to swap keys for values in a dictionary [duplicate]

I receive a dictionary as input, and would like to to return a dictionary whose keys will be the input's values and whose value will be the corresponding input keys. Values are unique.

For example, say my input is:

a = dict() a['one']=1 a['two']=2 

I would like my output to be:

{1: 'one', 2: 'two'} 

To clarify I would like my result to be the equivalent of the following:

res = dict() res[1] = 'one' res[2] = 'two' 

Any neat Pythonic way to achieve this?

like image 416
Roee Adler Avatar asked Jun 23 '09 10:06

Roee Adler


People also ask

How do dictionary handle duplicate keys?

If you want to keep duplicate keys in a dictionary, you have two or more different values that you want to associate with same key in dictionary. The dictionary can not have the same keys, but we can achieve a similar effect by keeping multiple values for a key in the dictionary.


1 Answers

Python 2:

res = dict((v,k) for k,v in a.iteritems()) 

Python 3 (thanks to @erik):

res = dict((v,k) for k,v in a.items()) 
like image 171
liori Avatar answered Oct 14 '22 03:10

liori