Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Checking for key and value in python dictionary

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading