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
  • 120,885
  • 29
  • 225
  • 225
user2105660
  • 103
  • 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
  • 122,243
  • 18
  • 242
  • 228
1
transposed = dict(zip(d.values(), d))
John La Rooy
  • 281,034
  • 50
  • 354
  • 495