python tuple to dict
Asked Answered
C

7

199

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.

Checkrein answered 24/9, 2010 at 1:4 Comment(0)
L
360

Try:

>>> t = ((1, 'a'),(2, 'b'))
>>> dict((y, x) for x, y in t)
{'a': 1, 'b': 2}
Lennielenno answered 24/9, 2010 at 1:7 Comment(5)
+1 Beautiful!, I had to try it with zip dict(zip(*zip(*t)[::-1])). This is slower, uglier and using way more memory..likely 3x.Tenno
@Tenno The wonderful thing about Python is that there are a hundred ways to express how to do something, each just as interesting as the next.Insurgent
Great, if what you have a is a triple you can do: dict((x, y) for x, y, z in t) or dict((x, (y, z)) for x, y, z in t) to get the second and third values as a tuple.Reparation
Also possible with a dict literal instead of a dict constructor: {y: x for x, y in t}Clearheaded
@bjd2385 Actually, this is a bit of a contradiction to clause 13 of PEP 20 (import this) ... All the same, it's true what you're saying.Bev
L
94

A slightly simpler method:

>>> t = ((1, 'a'),(2, 'b'))
>>> dict(map(reversed, t))
{'a': 1, 'b': 2}
Lynden answered 5/10, 2011 at 20:46 Comment(5)
what makes this faster ?Philbo
The map and dict functions are implement in C and are much faster than any python versionLynden
I like this for having the reverse explicitely spelled out.Sadye
@maazza: in general, performance tests suggest that (in the C implementation at least) map is faster than a comprehension when the thing being mapped is another built-in function (like reversed); in most other cases, the opposite is true. But it's better to profile than guess :)Peatroy
Nice! However, to my preference, the for expression looks slightly more obvious.Bev
O
53

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}
Oreste answered 2/3, 2013 at 21:20 Comment(0)
E
17
>>> 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}]
Exemplum answered 14/2, 2013 at 0:5 Comment(1)
You misunderstood the question - the point is how to swap keys and values. This simple conversion is already stated in the question itself.Bev
T
7

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]
Tights answered 10/4, 2016 at 1:15 Comment(2)
Removed dict.has_key() – use the in operator instead.Erek
d = dict() ## for x,y in t: d.setdefault(x,[]).append(y)Erek
P
3

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}
Positively answered 2/1, 2018 at 14:26 Comment(0)
M
-2

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

mydict=myty._asdict()
Maupin answered 3/1, 2023 at 6:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.