Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if string exist inside a list

Tags:

python

I have a list:

test = [{u'TopicArn': u'arn:aws:sns:us-east-1:700257:test1'},
  {u'TopicArn': u'arn:aws:sns:us-east-1:700257:test2'},
  {u'TopicArn': u'arn:aws:sns:us-east-1:700257:test3'},
  {u'TopicArn': u'arn:aws:sns:us-east-1:700257:test4'}]

And I want to check if a string exists in this above list.

string = "{u'TopicArn': u'arn:aws:sns:us-east-1:700257:test4'}"

if string in test:
   print("string exist in list")
else:
   print("string dont exist in list")

My variable string ha a string that exist inside the list but Im getting the message "string dont exist in list".

Do you understand why?

like image 882
techman Avatar asked Apr 01 '26 20:04

techman


1 Answers

These are the four things in test:

{u'TopicArn': u'arn:aws:sns:us-east-1:700257:test1'}
{u'TopicArn': u'arn:aws:sns:us-east-1:700257:test2'}
{u'TopicArn': u'arn:aws:sns:us-east-1:700257:test3'}
{u'TopicArn': u'arn:aws:sns:us-east-1:700257:test4'}

"arn:aws:sns:us-east-1:700257:test4" is not one of them, and the in comparison doesn't look deeper.

What you probably want to do is something like this:

if any(string in d.values() for d in test):

That checks whether the string is in the values of one of the dictionaries in test:

>>> string = "arn:aws:sns:us-east-1:700257:test4"
>>> string in test
False
>>> any(string in d.values() for d in test)
True
like image 99
Stefan Pochmann Avatar answered Apr 04 '26 11:04

Stefan Pochmann