-1

checking whether a key is present or not but it even though the key doesnt exist the below code evaluates to True.What is the correct and pythonic way of doing this

a={u'is_l': 0, u'importance': 1, u'release_id': u'12345', u'company': 1 }

if 'verision' and 'importance' in a: 
   //evaluates to True why ?
Rajeev
  • 44,985
  • 76
  • 186
  • 285

2 Answers2

0

Python adds parentheses for you like this:

if 'verision' and ('importance' in a):

Since all non-empty strings are truthy, this evaluates to True.

If you have more than two elements, it might be better to use all with a list:

if all(el in a for el in ['verision', 'importance', ...]):
Dzinx
  • 55,586
  • 10
  • 60
  • 78
  • Is there no other easier way of checking multiple keys rather than this way if 'verision' in a and 'importance' in a: – Rajeev Sep 22 '15 at 08:32
  • 1
    `all(element in a for element in ('verision', 'importance'))`. This will be more flexible if you don't have fixed values you want to check but a list of those. – Matthias Sep 22 '15 at 08:37
  • even though i have importance in this case it evaluates to false all(element in a for element in ( 'importance')) – Rajeev Sep 22 '15 at 08:43
  • 1
    If you have only one item in a tuple, you must suffix it with a comma: ('importance',). Alternatively, use a list: ['importance'] – Dzinx Sep 22 '15 at 08:44
0

Because the grouping of expressions would be like -

if ('verision') and ('importance' in a):

And 'version' string is True in boolean context (Only empty string is False in boolean context, all other non-empty strings are True, read more about it here). , so it short circuits the and condition and returns True. You want -

if 'verision' in a and 'importance' in a:

For only 2 keys i would suggest the above version , but if you have more than 2 keys , you can create a set of those keys as suggested in the comments by @Duncan and check if that set is a subset of the dictionary keys. Example -

needs = set(['version','importance','otherkeys'..])    #set of keys to check
if needs.issubset(a):                       #This can be written as a single line, but that would make the line very long and unreadable.

Demo -

>>> a={u'is_l': 0, u'importance': 1, u'notes': u'12345', u'created_by': 1 }
>>> needs=set(['verision','importance'])
>>> needs.issubset(a)
False
Community
  • 1
  • 1
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
  • Is there no other easier way of checking multiple keys rather than this way if 'verision' in a and 'importance' in a: – Rajeev Sep 22 '15 at 08:32
  • The easiest version (for 2 keys) would be this, are you having much more than 2 keys to check? – Anand S Kumar Sep 22 '15 at 08:36
  • 2
    For multiple keys: `needs=set(['verision','importance'])` and then you can say `if needs.issubset(a):` – Duncan Sep 22 '15 at 08:36