1

So I have 3 lists of data, I need to test if any of the data I get from the json response is in any of the lists, I'm probably being stupid about it but I'm trying to learn and can't seem to get it to work right.

list1 = ['a', 'b', 'c']
list2 = ['a1', 'b1', 'c1']
list2 = ['a2', 'b2', 'c2']

#block of code...
#block of code...

content = json.loads(response.read().decode('utf8'))
data = content
for x in data:
   #if x['name'] in list1: #This works fine the line below does not.
   if x['name'] in (list1, list2, list3):
   print("something")
3
  • What output are you getting? Commented Jul 28, 2015 at 14:57
  • It could be that it is checking to see if the value x['name'] matches fully and exactly any of the lists in (list1,list2,list3). Commented Jul 28, 2015 at 14:58
  • I was getting an "TypeError: unhashable type: 'list'" Commented Jul 28, 2015 at 15:21

3 Answers 3

1

I suggest something simple and straight-forward:

if (x['name'] in list1 or 
    x['name'] in list2 or 
    x['name'] in list3):
    ...
Sign up to request clarification or add additional context in comments.

1 Comment

While I liked Kasramvd's suggestion, I am choosing this method for simplicity and me making sure I can remember what I'm doing later and not having to scratch my head trying to figure it out again.
1

As a pythinc way for such tasks you can use any for simulating the OR operand and all for and operand.

So her you can use a generator expression within any() :

if any(x['name'] in i for i in (list1, list2, list3))

Comments

0

What about concatenating the lists?

if x['name'] in [list1 + list2 + list3]:

1 Comment

The downside is that this generates a new list object every time the if statement is reached. If the lists won't change, it is more efficient to move the concatenation outside the for loop.

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.