Mridang Agarwalla
Mridang Agarwalla

Reputation: 45008

Validating mutually exclusive elements in a dictionary

I have a dict that can have three keys url. link and path. These three need to be mutually exclusive when I'm validating the dict i.e. If the key url exists in the dict then path and link can't exist and so on...

To add to the complication: The main key cant be empty (null or '')

I've often come across scenarios like this and wrote a bunch of conditional statements to test this. Is there a better way?

Thanks.

Upvotes: 1

Views: 855

Answers (3)

inspectorG4dget
inspectorG4dget

Reputation: 113975

+1 to CatPlusPlus, but there's an issue in his code that I have commented on, but here's the fix:

if (url in d and d[url] not in [None, '']) ^ (link in d and d[link] not in [None, '']) ^ (path in d and d[path] not in [None, '']):
    # mutex condition satisfied
else:
    # at least two are keys in the dict or none are

Upvotes: 1

Cat Plus Plus
Cat Plus Plus

Reputation: 129764

To test your condition, you could do something like this:

# d is your dict
has_url  = bool(d.get('url',  False))
has_link = bool(d.get('link', False))
has_path = bool(d.get('path', False))
# ^ is XOR
if not (has_url ^ has_link ^ has_path):
    # either none of them are present, or there is more than one, or the
    # one present is empty or None

To find which one is present, and act on it, you probably still need three separate branches, though.

Upvotes: 4

Petar Ivanov
Petar Ivanov

Reputation: 93030

Maybe you shouldn't be using a dictionary, but rather a tuple:

(value, "url") or (value, "path") or (value, "link")

Upvotes: -1

Related Questions