alexa

Terse way of writing "if key1 or key2 are not in dict" in python ?

Terse way of writing "if key1 or key2 are not in dict" in python ?

One option would be to use not any or all and a list of keys to check different sets. Depending what logic you actually want to check there are several ways of doing it with these.

None of the keys are in the dict

 if not any(k in foo for k in ["bar", "baz"]): 

Any keys are missing from the dict

 if any(k not in foo for k in ["bar", "baz"]):
# or
if not all(k in foo for k in ["bar", "baz"]): 

All the keys are in the dict

 if all(k in foo for k in ["bar", "baz"]): 

If there are a lot of keys to check, you can pull it out into a separate list and keep the if statement constant length

 key_list = ["bar","bax","baz","bor","bam"]
if all(k in foo for k in key_list):

200 0
7

Write a Comments


* Be the first to Make Comment

GoodFirms Badge
GoodFirms Badge

Fix Your Meeting With Our SEO Consultants in India To Grow Your Business Online

Facebook
Twitter
LinkedIn
Instagram
Whatsapp
Call Now
Quick Inquiry