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?
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()}
transposed = dict(zip(d.values(), d))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With