Search code examples
python-3.xcoding-style

which one to use: if "key" not in dict VS if dict.get("key") is None #Python3


As Zen of Python says:

There should be one– and preferably only one –obvious way to do it.

I can't decide which one of the following lines is better:

ps.cfg is a python dict

    if cfg.get("runner") is None:
    if "runner" not in cfg:

Is one of them obviously better, or could we say that they are both OK?


Solution

  • It depends on what you want to achieve. If you want to make sure that an element at a certain key exists in that dictionary, i.e. something was inserted at that key, you should utilize capabilities that tell you exactly that. Like in your case:

    if "runner" not in cfg:
    

    If you really don't care if actually an element at a certain key exists in that dictionary and you just want to see if trying to retrieve an element of the dictionary will give you None as result, you can also work with the None check.

    Just consider that by calling get('some_key') and checking the returned value against None this won't tell you if there is an element existing at key some_key. Because no one prevents you from inserting an element without a value (meaning the value None) into a dictionary at that very key.