astrochris astrochris - 1 year ago 49
Python Question

checking multiple keys in a dictionary is not working. python

I am writing an if statement to determine if my dictionary has multiple keys. If not i just want to pass. I thought if the code below did not find 'redshift' as a key it would pass. However when i run it redshift is not a key and it does not pass. I get a Key error. What is the problem. As long as it finds 'redshift' or 'host' it is not passing.

print config[name].keys()
if ("redshift" and "host") in config[name]:
print config[name].keys()


The expression ("redshift" and "host") in config[name] does not test if both keys are present.

("redshift" and "host") produces just "host", because and returns either the first expression if false according to its truth value, otherwise the second expression is returned. So in the end, all you are really testing is the expression "host" in config[name].

Use two separate in tests:

if "redshift" in config[name] and "host" in config[name]:

or test for with a set against the dictionary with set.issubset():

if {'redshift', 'host'}.issubset(config[name]):