Reputation: 2262
How I can make a conditional in python that checks for this three keywords defined in the dictionary and that they are not False
?
settings = {
'proxy_host': '127.0.0.1',
'proxy_port': 8080,
'proxy_protocol': 'socks',
}
I have tried with the sentence you can see below. But this is only checking that these keywords exists in the dictionary settings
without bothering about what type of value has.
if 'proxy_host' and 'proxy_port' and 'proxy_protocol' in settings:
I only want my IF to True If none of the keywords are falsely and they all exist as keys.
Upvotes: 2
Views: 86
Reputation: 1834
if ('proxy_host' in settings and isinstance(settings['proxy_host'], str))
and ('proxy_port' in settings and isinstance(settings['proxy_port'], int))
and ('proxy_protocol' in settings and isinstance(settings['proxy_protocol']), str)):
Upvotes: 2
Reputation: 19030
Use a simple generator expression and all()
:
if all(d.get(k) for k in keys):
Example:
keys = ['proxy_host', 'proxy_port', 'proxy_protocol']
if all(settings.get(k) for k in keys):
print("Settings good!")
else:
print("Missing setting!")
Upvotes: 1
Reputation: 59114
If you want to check that all of the keys are in the dict and map to a non-falsey value, you can check this:
if all(settings.get(x) for x in ['proxy_host','proxy_port', 'proxy_protocol']):
dict.get(key)
will return None
if the key is not in the dict
, so you you can check "is in the dict and value is not falsey" in one go.
Upvotes: 1