Python: best way to exchange keys with values โ€‹โ€‹in a dictionary?

I get the dictionary as input and would like to return a dictionary whose keys will be the input values โ€‹โ€‹and whose value will correspond to the corresponding input keys. The values โ€‹โ€‹are unique.

For example, say my input is:

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

I would like my conclusion to be:

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

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

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

Any neat python way to achieve this?

thank

+77
python dictionary
Jun 23 '09 at 10:53
source share
17 answers

Python 2:

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

Python 3 (thanks @erik):

 res = dict((v,k) for k,v in a.items()) 
+118
Jun 23 '09 at 11:00
source share
 new_dict = dict (zip(my_dict.values(),my_dict.keys())) 
+51
Jul 06 '09 at 16:09
source share

From Python 2.7, including 3.0+, there is perhaps a shorter, more readable version:

 >>> my_dict = {'x':1, 'y':2, 'z':3} >>> {v: k for k, v in my_dict.items()} {1: 'x', 2: 'y', 3: 'z'} 
+44
Jul 6 '09 at 16:36
source share
 In [1]: my_dict = {'x':1, 'y':2, 'z':3} In [2]: dict((value, key) for key, value in my_dict.iteritems()) Out[2]: {1: 'x', 2: 'y', 3: 'z'} 
+30
Jul 06 '09 at 15:43
source share

You can use verbal understanding :

 res = {v: k for k, v in a.iteritems()} 

Edited: for Python 3, use a.items() instead of a.iteritems() . A discussion of the differences between the two can be found in the Python iterations for SO.

+25
Aug 4 '13 at 13:21
source share

You can try:

 d={'one':1,'two':2} d2=dict((value,key) for key,value in d.iteritems()) d2 {'two': 2, 'one': 1} 

Remember that you cannot "flip" a dictionary if

  • More than one key have the same value. For example {'one':1,'two':1} . A new dictionary can contain only one element with key 1 .
  • One or more values โ€‹โ€‹are not reset. For example {'one':[1]} . [1] is a valid value, but not a valid key.

See this thread on the python mailing list for a discussion of the topic.

+18
Jun 23 '09 at 11:02
source share
 new_dict = dict( (my_dict[k], k) for k in my_dict) 

or even better, but only works in Python 3:

 new_dict = { my_dict[k]: k for k in my_dict} 
+14
Jul 06 '09 at 15:46
source share

res = dict(zip(a.values(), a.keys()))

+13
Jun 23 '09 at 10:55
source share

Another way to extend the answer to Ilya Prokin is to actually use the reversed function.

 dict(map(reversed, my_dict.items())) 

In essence, your dictionary is iterated through (using .items() ), where each element is a key / value pair, and these elements are exchanged using the reversed function. When this is passed to the dict constructor, it turns them into the value / key pairs you want.

+10
Mar 09 '16 at 23:53 on
source share

The current lead answer suggests that the values โ€‹โ€‹are unique, which is not always the case. What if the values โ€‹โ€‹are not unique? You will lose information! For example:

 d = {'a':3, 'b': 2, 'c': 2} {v:k for k,v in d.iteritems()} 

returns {2: 'b', 3: 'a'} .

Information about 'c' been completely ignored. Ideally, this should have been something like {2: ['b','c'], 3: ['a']} . This is what the bottom implementation does.

 def reverse_non_unique_mapping(d): dinv = {} for k, v in d.iteritems(): if v in dinv: dinv[v].append(k) else: dinv[v] = [k] return dinv 
+9
Aug 03 '17 at 23:20
source share

Recommendation for improving Javier's answer:

 dict(zip(d.values(),d)) 

Instead of d.keys() you can write only d , because if you go through a dictionary with an iterator, it will return the keys of the corresponding dictionary.

Ex. for this behavior:

 d = {'a':1,'b':2} for k in d: k 'a' 'b' 
+6
Jul 28 '11 at 7:53
source share
 dict(map(lambda x: x[::-1], YourDict.items())) 

.items() returns a list of tuples (key, value) . map() goes through the elements of the list and applies lambda x:[::-1] to each of its elements (tuple) to cancel it, so each tuple becomes (value, key) in a new list displayed from the map. Finally, dict() makes a dict from the new list.

+2
Aug 07 '15 at 21:09
source share

Can be easily done with a dictionary understanding:

 {d[i]:i for i in d} 
+2
Jul 15 '18 at 14:48
source share

Using loop : -

 newdict = {} #Will contain reversed key:value pairs. for key, value in zip(my_dict.keys(), my_dict.values()): # Operations on key/value can also be performed. newdict[value] = key 
+1
May 03 '14 at 7:05
source share

If you are using Python3, it is a little different:

 res = dict((v,k) for k,v in a.items()) 
+1
Aug 09 '14 at 17:42 on
source share

Adding a solution in place:

 >>> d = {1: 'one', 2: 'two', 3: 'three', 4: 'four'} >>> for k in list(d.keys()): ... d[d.pop(k)] = k ... >>> d {'two': 2, 'one': 1, 'four': 4, 'three': 3} 

In Python3, it is very important to use list(d.keys()) , because dict.keys returns the kind of keys. If you are using Python2, d.keys() enough.

+1
Apr 15 '16 at 7:17
source share
 res = dict(zip(a.values(), a.keys())) 
0
Jun 22 '19 at 10:14
source share



All Articles