Home > database >  Terse way of writing "if key1 or key2 are not in dict" Python
Terse way of writing "if key1 or key2 are not in dict" Python

Time:05-03

Simple question, just wondering if there's a shorter way to check for a key being in a dict than writing it out twice like this:

if "bar" not in foo.keys() or "baz" not in foo.keys():

CodePudding user response:

You do not need to call keys

if "bar" not in foo or "baz" not in foo:

CodePudding user response:

if "bar" not in foo.keys() or "baz" not in foo.keys():

is the same as:

if "bar" not in foo or "baz" not in foo:

is the same as:

if not ("bar" in foo and "baz" in foo):

is the same as:

if not all(key in foo for key in ("bar", "baz")):

is the same as:

if not {"bar", "baz"}.issubset(foo):

The latter is what I'd use, especially if I had a bunch of values to test.

CodePudding user response:

Assuming foo is a dictionary, you don't need to write .keys().

"bar" in foo will work and is shorter.

Using any() is bit neater but not really shorter:

if any(x not in foo for x in ["bar", "baz"]):

If you were checking for more than two keys, any() would definitely be shorter.

CodePudding user response:

One option would be to use not any or all and a list of keys to check different sets. Depending what logic you actually want to check there are several ways of doing it with these.

None of the keys are in the dict

if not any(k in foo for k in ["bar", "baz"]):

Any keys are missing from the dict

if any(k not in foo for k in ["bar", "baz"]):
# or
if not all(k in foo for k in ["bar", "baz"]):

All the keys are in the dict

if all(k in foo for k in ["bar", "baz"]):

If there are a lot of keys to check, you can pull it out into a separate list and keep the if statement constant length

key_list = ["bar","bax","baz","bor","bam"]
if all(k in foo for k in key_list):
  • Related