0

I'm having trouble comparing a nested list with a dictionary of multiple values. The dictionary and nested list are like so:

list = [[['a']], [['b']], [['c'], ['d']], [['e'], ['f'], ['g']]]

dict = {'adv0' : ('a', 'b'), 'adv1' : ('f', 'c'), 'adv2' : ('d', 'e', 'q')}

I want to create an array where each sublist ('a', 'b', 'c & d', 'e & f & g') is compared to each value and if any item in the sublist is a member of that value it creates a 0 entry, otherwise it creates a 1 entry.

[0, 1, 1] since 'a' is only in adv0, [0, 1, 1] since 'b' is only in adv0, [1, 0, 0] since adv1 and adv2 contain 'c' or 'd', [1, 0, 0] since adv1 and adv2 contain one of 'e', 'f' or 'g'. Hence we get the array [0,1,1,0,1,1,1,0,0,1,0,0].

The following code is my horrible attempt at a solution which doesn't work:

l = []
for sublist in list:
      for items in sublist:
        for x in items:
          for key in dict:
            if x in dict[key]:
              l.extend('0')
            elif x not in dict[key]:
              l.extend('1')
print l
1
  • Note that dictionaries are not ordered. It sounds like you want the resulting list ordered by a natural sort on the dict keys -- but it would be good to mention that explicitly. Commented Oct 6, 2014 at 21:03

2 Answers 2

1

One problem is dictionaries are unordered, so you may not iterate through the keys as you expect. use an OrderedDict or iterate specifically through the keys you want. This works:

L = [[['a']], [['b']], [['c'], ['d']], [['e'], ['f'], ['g']]]
D = {'adv0' : ('a', 'b'), 'adv1' : ('f', 'c'), 'adv2' : ('d', 'e', 'q')}

l = []
for sublist in L:
    for key in ('adv0','adv1','adv2'):
        if any(item[0] in D[key] for item in sublist):
            l.append(0) # changed to give explicit output you listed.
        else:
            l.append(1) # ditto
print l

Output:

[0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0]
Sign up to request clarification or add additional context in comments.

Comments

1

Here you go: (I renamed the input to lst and dct to avoid conflicting with the built-in list and dict objects)

[0 if any(v[0] in dct[k] for v in sublst) else 1 
   for sublst in lst 
     for k in sorted(dct.keys())]

That was fun. (But, sadly, 3 minutes too late...)

1 Comment

I was quite surprised how similar out solutions were.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.