user3481663
user3481663

Reputation: 79

Looping through nested list that contains dictionary

Hi how can I loop through n below, and get the dictionary elements in e if the elements are a match.

e = [(1001, 7005, {'length': 0.35, 'modes': 'cw', 'type': '99', 'lanes': 9}),
     (1002, 8259, {'length': 0.35, 'modes': 'cw', 'type': '99', 'lanes': 9}), (1001, 14007, {'length': 0.35, 'modes': 'cw', 'type': '99', 'lanes': 9})]

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

ie compare n and if n is in e print the dictionary

b = []
for d in n:
    for items in d:
        print b

outcome should be

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

Upvotes: 2

Views: 86

Answers (3)

venpa
venpa

Reputation: 4318

You can use list comprehension:

[e1[2] for e1 in e for n1 in n for n2 in n1 if (e1[0]==n2[0] and e1[1]==n2[1])]

Output:

[{'lanes': 9, 'length': 0.35, 'type': '99', 'modes': 'cw'}, 
 {'lanes': 9, 'length': 0.35, 'type': '99', 'modes': 'cw'}]

Upvotes: 0

alecxe
alecxe

Reputation: 473833

You need to create a mapping (dictionary) from the e list and flatten n list of list of tuples into list of tuples:

e = [(1001, 7005, {'length': 0.35, 'modes': 'cw', 'type': '99', 'lanes': 9}),
     (1002, 8259, {'length': 0.35, 'modes': 'cw', 'type': '99', 'lanes': 9}),
     (1001, 14007, {'length': 0.35, 'modes': 'cw', 'type': '99', 'lanes': 9})]

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

d = {(item[0], item[1]): item[2] for item in e}
n = [item for sublist in n for item in sublist]

print [d[item] for item in n if item in d]

prints:

[{'lanes': 9, 'length': 0.35, 'type': '99', 'modes': 'cw'}, 
 {'lanes': 9, 'length': 0.35, 'type': '99', 'modes': 'cw'}]

Upvotes: 1

thefourtheye
thefourtheye

Reputation: 239443

You can convert the e list to a dictionary, with dictionary comprehension, like this

f = {(v1, v2):v3 for v1, v2, v3 in e}

Then, we can flatten n and check if each of the element is in f or not. If it is there, then we can get the value corresponding to that from f, like this

from itertools import chain
print [f[item] for item in chain.from_iterable(n) if item in f]

Output

[{'lanes': 9, 'length': 0.35, 'modes': 'cw', 'type': '99'},
 {'lanes': 9, 'length': 0.35, 'modes': 'cw', 'type': '99'}]

Upvotes: 1

Related Questions