Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check to see if a collection of properties exist inside a dict object in Python

What is a good way to check to see if a collection of properties exist inside a dict object in Python?

Currently we are doing this, but it seems like there may be a better way:

properties_to_check_for = ['name', 'date', 'birth']
for property in properties_to_check_for:
    if property not in dict_obj or dict_obj[property] is None:
        return False

Thanks so much!

like image 386
Chris Dutrow Avatar asked Sep 07 '25 16:09

Chris Dutrow


2 Answers

You can use all with a generator:

all(key in dict_obj for key in properties_to_check_for)

It'll short-circuit, just like your for loop. Here's a direct translation of your current code:

all(dict_obj.get(key) is not None for key in properties_to_check_for)

d.get(key) will return None if the key isn't in your dictionary, so you don't really need to check if it's in there beforehand.

like image 137
Blender Avatar answered Sep 09 '25 06:09

Blender


You could use any():

any(dict_obj.get(prop) is None for prop in properties_to_check_for )

This will return True if any property is not found in properties_to_check_for or if it's value is None.

like image 21
Ashwini Chaudhary Avatar answered Sep 09 '25 06:09

Ashwini Chaudhary