7

I have the dictionary

d = {'a':3, 'b':7, 'c':8}

I was wondering how could i reverse the order of the dictionary in order to make it look like this:

d = {3:'a', 7:'b', 8:'c'}

I would like to do this without just writing it like this. Is there a way i can use the first dict in order to obtain the new result?

jamylak
  • 128,818
  • 30
  • 231
  • 230
user2105660
  • 101
  • 4

2 Answers2

12

Yes. You can call items on the dictionary to get a list of pairs of (key, value). Then you can reverse the tuples and pass the new list into dict:

transposed = dict((value, key) for (key, value) in my_dict.items())

Python 2.7 and 3.x also have dictionary comprehensions, which make it nicer:

transposed = {value: key for (key, value) in my_dict.items()}
icktoofay
  • 126,289
  • 21
  • 250
  • 231
2
transposed = dict(zip(d.values(), d))
John La Rooy
  • 295,403
  • 53
  • 369
  • 502