2

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.
NIlesh Sharma
  • 5,445
  • 6
  • 36
  • 53

4 Answers4

11

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()}
Fedor Gogolev
  • 10,391
  • 4
  • 30
  • 36
2

If I understood properly, you're almost there:

>>> ivd={v:k for (k,v) in a.items()}
>>> ivd
{122: 'a', 123: 'b', 333: 'd', '233': 'e'}

(Credit should go to stummjr for this: https://stackoverflow.com/a/11977757/289011 )

Community
  • 1
  • 1
Savir
  • 17,568
  • 15
  • 82
  • 136
0

Why not just

ivd = {a[key]:key for key in a}

where a is your dict? It seems much simpler. In python, you can directly iterate over the keys of a dict.

Snakes and Coffee
  • 8,747
  • 4
  • 40
  • 60
0

Here are two ways how it can be done:

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

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


# Use to invert dictionaries that have unique values
inverted_dict = dict(map(reversed, a.items()))
assert inverted_dict == expected, "1st"

# Use to invert dictionaries that have unique values
inverted_dict = {value: key for key, value in a.items()}
assert inverted_dict == expected, "2nd"

print("PASSED!!!")
Vlad Bezden
  • 83,883
  • 25
  • 248
  • 179