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

Check for multiple value pairs in dictionary

Is there a way to shorten this code?

I want to print something if both a, b is in the dic, or a-foo, b-foo is in the dic or a-bar, b-bar is in the dic. Consider -foo and -bar to be fixed values.

Can I join the multiple if-s with or statements?

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

The dict looks like this:

defaultdict(<class 'set'>, {'key1': {'elem1', 'elem2'}})
if "a" in my_dic["key1"] and "b" in my_dic["key1"]:
    print("Exists")
if "a-foo" in my_dic["key1"] and "b-foo" in my_dic["key1"]:
    print("Exists")
if "a-bar" in my_dic["key1"] and "b-bar" in my_dic["key1"]:
    print("Exists") 

>Solution :

This nicely generalizes to N entries.

valuepairs = (("a", "b"), ("a-foo", "b-foo"), ("a-bar", "b-bar"))
if any(all(key in my_dic["key1"] for key in pair) for pair in valuepairs):
    print("Exists")
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