Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse the one-to-one mapped dictionary

Suppose there is a dictionary

a = {'a':122,'b':123,'d':333,'e':'233'}

Now I want to revert it as its a one-to-one dictionary so we can do that.

What I have tried:

In [67]: ivd=[(v,k) for (k,v) in a.items()]

In [68]: ivd
Out[68]: [(122, 'a'), (123, 'b'), ('233', 'e'), (333, 'd')]

Now may be some how We can convert this ivd into a dictionary. My questions are

  1. How to change this ivd into a dictionary ?
  2. Is there any more pythonic solution available to do this? which I think it should be there.
like image 800
NIlesh Sharma Avatar asked Dec 20 '25 11:12

NIlesh Sharma


1 Answers

You can use dict constructor:

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

or dict comprehension in python 2.7 or later:

ivd = {v: k for (k, v) in a.items()}
like image 117
Fedor Gogolev Avatar answered Dec 23 '25 00:12

Fedor Gogolev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!