0

Is there a better way to write the following:

if "msg" in response_dic or "save_act_errors" in response_dic  or "add_act_errors" in response_dic  or "modif_act_errors" in response_dic  or "update_act_errors" in response_dic:
    #do stuff

response_dic is a dictionary, I am checking for keys.

There are 2 questions in fact:

1/ How to test many keys in a dictionary?

2/ How to check partial keys (in my case finishing with "_act_errors")?

rom
  • 3,592
  • 7
  • 41
  • 71
  • You're right, it's a similar problem, but in my situation I have to use any and not all. – rom Sep 18 '13 at 02:05

2 Answers2

2
>>> keys = ['msg','save_act_errors']
>>> d = { 'msg':1 }
>>> any(key in d for key in keys)
True

Or

>>> keys | set(d)
HennyH
  • 7,794
  • 2
  • 29
  • 39
  • You need two `set`s for the `|` operator... and furthermore, `set(keys) & set(d)` would make more sense! – opatut Sep 18 '13 at 02:06
  • The `any` operator is exactly what I need. But I think using a `set` would be slower, right? – rom Sep 18 '13 at 02:09
2

Yes! there is a better way:

keys = ["msg", "save_act_errors", "add_act_errors", "modif_act_errors", ...]

if any(key in response_dic for key in keys):
    #do stuff
juliomalegria
  • 24,229
  • 14
  • 73
  • 89
  • Good idea! It is shorter to write but is it as efficient? – rom Sep 18 '13 at 02:07
  • The `any()` is doing exactly the same you were doing. It will stop and return `True` when it find the first expression that evaluates to `True`, otherwise will return `False`. – juliomalegria Sep 18 '13 at 03:50