user2868810
user2868810

Reputation: 47

Nested list with dictionary as content

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

lst1 = [[(10, 70, {'a': 0.30}),
         (12, 82, {'b': 0.35})],
        [(11, 140, {'c': 0.54}),
         (99, 25, {'d': 0.57})]
       ]

lst2 = [[(10, 70), (32, 25),(12,82)],
        [(1598, 6009), (11,140), (33,66), (99,25)]
       ]

ie compare lst2 and if lst2 is in lst1 print the dictionary.

outcome should look like so:

outcome = [[{'a': 0.30}, {'b':0.35}], [{'c': 0.54}, {'d':0.57}]]

Thanks

Sorry an update on this one would be if lst1 is not nested ie

lst1 = [(10, 70, {'a': 0.30}),
        (12, 82, {'b': 0.35}),
        (11, 140, {'c': 0.54}),
        (99, 25, {'d': 0.57})
       ]

lst2 = [[(10, 70), (32, 25),(12,82)],
        [(1598, 6009), (11,140), (33,66), (99,25)]
       ]

such that the same outcome will be arrived at

Upvotes: 2

Views: 80

Answers (2)

thefourtheye
thefourtheye

Reputation: 239443

You can flatten lst1 and convert that to a dictionary with dictionary comprehension, so that the lookups will be faster. Once the dictionary is constructed, you just have to iterate lst2 and if the element is a key in the dictionary, then get the corresponding dictionary value.

from itertools import chain
d = {(item[0], item[1]):item[2] for item in chain.from_iterable(lst1)}
print d
# {(12,82):{'b':0.3}, (10,70):{'a':0.3}, (11,140):{'c':0.54}, (99,25):{'d':0.57}}
print [[d[item] for item in items if item in d] for items in lst2]
# [[{'a': 0.3}, {'b': 0.3}], [{'c': 0.54}, {'d': 0.57}]]

If the input is not nested, like in the updated question, you don't need chaining. You can simply do

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

Upvotes: 2

Paul Draper
Paul Draper

Reputation: 83225

For each pair, create a dict for the elements from lst1 (for performance) and then check for each of the elements from lst2.

outcome = []
for lst_a, lst_b in zip(lst1, lst2):
    lookup = {a[:-1]:a[-1] for a in lst_a}
    outcome.append([lookup[b] for b in lst_b if b in lookup])
print outcome

Upvotes: 1

Related Questions