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!
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With