0

Right now I have two lists that I am trying to combine into a dictionary with a key being an element of list A and that maps to a list of compared values from list B.

These are lists of objects. I am filtering the objects by equal module values.

say A list is [ a1, a2, a3 ] and B list is [ b1, b2, b3, b4] . I compare each B list value with each A list value in the nested for loops. If they have the same module value, then the b_value is appended to z, a new list containing only b_values that match a certain a_value module. The new list z should be the value for an a_value key with the same module as the z list (filtered b_values)

Consider:

listA = []   # every a value in list a should be a key
listB = []   #contains many b values that must be filtered
execute = {}

for i in listA:
     z = []
     for j in listB:
          if j.module == i.module
               z.append(j)
     execute[i] = z                   # append full list as value for
                                      # key x

Although this doesn't seem to construct the dictionary the way I am expecting.

the dict could end up looking something like this: { a1: [b2, b3, b7] a2: [b1, b2, b6, b9] a3: [b4, b11]}

Am I approaching this the right way? I saw that tuples could be an option for this but I don't see how.

Any help is appreciated! Thanks

Lamar
  • 540
  • 4
  • 21

1 Answers1

0

You made only one simple mistake. execute[i] = z

Try this as an exmaple (filter removed for simplicity):

import sys

listA = []
listB = []
execute = {}

listA.append("A1")
listA.append("A2")
listB.append("B1")
listB.append("B2")

for i in listA:
     z = []
     for j in listB:
        z.append(j)
     execute[i] = z

print execute
Dylan Kapp
  • 224
  • 3
  • 8
  • Output is {'A1': ['B1', 'B2'], 'A2': ['B1', 'B2']} – Dylan Kapp Feb 18 '16 at 21:42
  • Thanks, that was a typo in my example. My real problem actually turned out to be that I had defined my own objects and did not have a __eq__ function defined. Comparison during my filter was always false. – Lamar Feb 19 '16 at 05:21
  • Ahhh, that would explain it. Glad its figured out :) – Dylan Kapp Feb 19 '16 at 15:53