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.
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.
+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
Maybe you shouldn't be using a dictionary, but rather a tuple:
(value, "url") or (value, "path") or (value, "link")
精彩评论