Jake
Jake

Reputation: 13141

python swapped tuple to dict

For the tuple, t = ((1, 'a'),(2, 'b')) dict(t) returns {1: 'a', 2: 'b'}

Is there a good way to get {'a': 1, 'b': 2} (keys and vals swapped)?

Ultimately, I want to be able to return 1 given 'a' or 2 given 'b', perhaps converting to a dict is not the best way.

Upvotes: 207

Views: 328206

Answers (8)

Rarblack
Rarblack

Reputation: 4664

The easiest way is:

>>> t = ((1, 'a'),(2, 'b'))
>>> {key: value for value, key in t}
{'a': 1, 'b': 2}

The answer is the same as the accepted one; however, it is better regarding readability.

Upvotes: 0

Vinayak Thatte
Vinayak Thatte

Reputation: 593

With Python 3.6 and above, it's a function:

mydict=myty._asdict()

Upvotes: -3

Gunnarsson
Gunnarsson

Reputation: 544

>>> dict([('hi','goodbye')])
{'hi': 'goodbye'}

Or:

>>> [ dict([i]) for i in (('CSCO', 21.14), ('CSCO', 21.14), ('CSCO', 21.14), ('CSCO', 21.14)) ]
[{'CSCO': 21.14}, {'CSCO': 21.14}, {'CSCO': 21.14}, {'CSCO': 21.14}]

Upvotes: 17

Vlad Bezden
Vlad Bezden

Reputation: 89527

Here are couple ways of doing it:

>>> t = ((1, 'a'), (2, 'b'))

>>> # using reversed function
>>> dict(reversed(i) for i in t)
{'a': 1, 'b': 2}

>>> # using slice operator
>>> dict(i[::-1] for i in t)
{'a': 1, 'b': 2}

Upvotes: 3

psun
psun

Reputation: 635

If there are multiple values for the same key, the following code will append those values to a list corresponding to their key,

d = dict()
for x,y in t:
    if(d.has_key(y)):
        d[y].append(x)
    else:
        d[y] = [x]

Upvotes: 7

autholykos
autholykos

Reputation: 866

Even more concise if you are on python 2.7:

>>> t = ((1,'a'),(2,'b'))
>>> {y:x for x,y in t}
{'a':1, 'b':2}

Upvotes: 56

jterrace
jterrace

Reputation: 67063

A slightly simpler method:

>>> t = ((1, 'a'),(2, 'b'))
>>> dict(map(reversed, t))
{'a': 1, 'b': 2}

Upvotes: 99

Greg Hewgill
Greg Hewgill

Reputation: 992945

Try:

>>> t = ((1, 'a'),(2, 'b'))
>>> dict((y, x) for x, y in t)
{'a': 1, 'b': 2}

Upvotes: 370

Related Questions