I need to check if key exists in Python dictionary and value of that is not null/empty for multiple keys before processing further.
exception = False
if 'key1' in d and d['key1']:
pass
else:
exception = True
if 'key2' in d and d['key2']:
pass
else:
exception = True
if 'key3' in d and d['key3']:
pass
else:
exception = True
if not exception:
#Process it
I feel this code is very ugly and not Pythonic as well.
Can we write the logic better?
>Solution :
You can use all and a generator:
if all(k in d and d[k] for k in ['key1', 'key2', 'key3']):
pass
else:
exception = True
You could actually skip using a flag:
if not all(k in d and d[k] for k in ['key1', 'key2', 'key3']):
# process
or
if any(k not in d or not d[k] for k in ['key1', 'key2', 'key3']):
# process