Search for values ​​and keys from dictionaries and check them

Given a dictionary:

data = [{'id':'1234','name':'Jason','pw':'*sss*'}, {'id':'2345','name':'Tom','pw': ''}, {'id':'3456','name':'Art','pw': ''}, {'id':'2345','name':'Tom','pw':'*sss*'}] 

I need to find that pw always contains '' or *sss* .

I tried to do this:

 for d in data: if d['pw'] == ['*sss*' or ''] print "pw verified and it is '*sss*' or '' " else: print "pw is not any of two'*sss*' or ''" 

Please help me fill this out. I need to find that pw always contains ' ' or '*sss*' .

If possible, I need to do this on one line.

+4
source share
3 answers

['*sss*' or ''] returns ['*sss*'] because '' is False, and *sss* is considered True.

This means that your list is read as [True or False] . And the True factor is selected (in this case *sss* .

You would probably want to do something like:

 if d['pw'] in ['*sss*', '']: 

Or even:

 if d['pw'] == '*sss*' or d['pw'] == '': 

As a single insert (view):

 >>> for res in ("pw verified and it is '*sss*' or '' " if i['pw'] in ['*sss', ''] else "pw is not any of two'*sss*' or ''" for i in data): ... print res ... pw is not any of two'*sss*' or '' pw verified and it is '*sss*' or '' pw verified and it is '*sss*' or '' pw is not any of two'*sss*' or '' 
+4
source

Use set to do this on one separate line .

 ans = {d['pw'] for d in data}.issubset({'','*sss*'}) 

ans True if d['pw'] always '' or '*sss*' else False

+1
source

If you are looking for one liner, use the all() function.

 >>> data = [{'id':'1234','name':'Jason','pw':'*sss*'}, {'id':'2345','name':'Tom','pw': ''}, {'id':'3456','name':'Art','pw': ''}, {'id':'2345','name':'Tom','pw':'*sss*'}] >>> all(elem['pw'] in ('', '*sss*') for elem in data) True 

For the condition if .

 >>> "pw verified" if all(elem['pw'] in ('', '*sss*') for elem in data) else "pw not verified" 'pw verified' 
0
source

Source: https://habr.com/ru/post/1492450/


All Articles