2

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]
kezzos
  • 3,023
  • 3
  • 20
  • 37
  • Related: [Efficient bidirectional hash table in Python?](http://stackoverflow.com/questions/3318625/efficient-bidirectional-hash-table-in-python), [Two way/reverse map](http://stackoverflow.com/questions/1456373/two-way-reverse-map) – GingerPlusPlus Oct 31 '16 at 12:15
  • Thanks that is basically what I am after, a poor mans bidirectional hash in this case – kezzos Oct 31 '16 at 12:18

3 Answers3

4

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)}
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
2
from itertools import chain
flatten = chain.from_iterable

a = [(1, 2), (3, 4), (5, 6)]
d = dict(flatten(((k, (k, v)), (v, (k, v))) for k, v in a))

print(d)
GingerPlusPlus
  • 5,336
  • 1
  • 29
  • 52
0

Dictionary comprehensions:

{**{k: (k, v) for k, v in a}, **{v: (k, v) for k, v in a}}
GingerPlusPlus
  • 5,336
  • 1
  • 29
  • 52