Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the dictionary function? [duplicate]

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?

like image 413
user2105660 Avatar asked Apr 04 '13 05:04

user2105660


2 Answers

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()}
like image 108
icktoofay Avatar answered Nov 14 '22 23:11

icktoofay


transposed = dict(zip(d.values(), d))
like image 27
John La Rooy Avatar answered Nov 14 '22 22:11

John La Rooy