user3481663
user3481663

Reputation: 79

Building tuples from nested lists

Hi please how can I append the tuples in a nested list to list of dictionaries to form a new list of tuples as follow:

nde = [{'length': 0.35, 'modes': 'cw', 'type': '99', 'lanes': 9},
           {'length': 0.48, 'modes': 'cw', 'type': '99', 'lanes': 9},
           {'length': 0.88, 'modes': 'cw', 'type': '99', 'lanes': 9}]

dge = [[(1001, 7005),(3275, 8925)], [(1598,6009),(1001,14007)]]

How can I append them to have the outcome formatted thus:

rslt = [(1001, 7005, {'length': 0.35, 'modes': 'cw', 'type': '99', 'lanes': 9}... ]

I tried this:

[(k1[0], k1[1], k2) for k1, k2 in zip(dge, nde)]

but it doesnt give the desired result. Thanks

Upvotes: 4

Views: 72

Answers (2)

m.wasowski
m.wasowski

Reputation: 6387

You have nested list, so you should flatten them before ziping:

import itertools
[(k1[0], k1[1], k2) for k1, k2 in zip(itertools.chain(*dge), nde)]

Upvotes: 3

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250961

You need to flatten the list of lists first and then use it with zip:

>>> from itertools import chain
>>> [(k1[0], k1[1], k2) for k1, k2 in zip(chain.from_iterable(dge), nde)]
[(1001, 7005, {'lanes': 9, 'length': 0.35, 'type': '99', 'modes': 'cw'}),
 (3275, 8925, {'lanes': 9, 'length': 0.48, 'type': '99', 'modes': 'cw'}),
 (1598, 6009, {'lanes': 9, 'length': 0.88, 'type': '99', 'modes': 'cw'})]

Docs: itertools.chain.from_iterable

Upvotes: 4

Related Questions