2

I have list of dictionaries each key mapped to list

[    {28723408: [28723409]},
     {28723409: [28723410]},
     {28723410: [28723411, 28723422]},
     {28723411: [28723412]},
     {28723412: [28723413]},
     {28723413: [28723414, 28, 28723419]}]

I want to create list of tuples key mapped to each list value:

[(28723408, 28723409),
 (28723409, 28723410),
 (28723410, 28723411),
 (28723410, 28723422),
 (28723411, 28723412),
 (28723412, 28723413),
 (28723413, 28723414),
 (28723413, 28),
 (28723413, 28723419),]

I did it following way:

for pairs in self.my_pairs:
    for source, targets in pairs.items():
        for target in targets:
            pair_list.append((source, target))

Is there more Pythonic way doing so ?

Night Walker
  • 20,638
  • 52
  • 151
  • 228

1 Answers1

3

I would do exactly what you have already done, but using a list comprehension.

pair_list = [(source, target)
             for pairs in self.my_pairs
             for source, targets in pairs.items()
             for target in targets]

This approach might look identical to yours, but it is much faster! Check for example this question (or this). This fact is confirmed also here.

If you want a more "pythonic" approach you could also use itertools.product and itertools.chain:

from itertools import chain, product

pair_list = list(chain(*(product((source,), targets)
                         for pairs in self.my_pairs
                         for source, targets in pairs.items())))
Riccardo Bucco
  • 13,980
  • 4
  • 22
  • 50