kezzos kezzos - 1 month ago 10
Python Question

Convenient way to create a map for list of tuples

For a list of tuples with unique values such as:

a = [(1, 2), (3, 4), (5, 6)]


I would like to create a map:

b = {}
for t in a:
for tt in t:
b[tt] = t

>>> {1: (1, 2), 2: (1, 2), 3: (3, 4), 4: (3, 4), 5: (5, 6), 6: (5, 6)}


Is there a nicer/convenient way to achieve this without the explicit for loop? One way might be to use
dict.update
although this could get ugly with many items in the tuple:

[(b.update({t1: (t1, t2)}), b.update({t2: (t1, t2)})) for t1, t2 in a]

Answer

Use a dictionary comprehension:

>>> a = [(1, 2), (3, 4), (5, 6)]
>>> {i: tup for tup in a for i in tup}
{1: (1, 2), 2: (1, 2), 3: (3, 4), 4: (3, 4), 5: (5, 6), 6: (5, 6)}
Comments