I have a dict in python that follows this general format:
{'field': ['$.name'], 'group': 'name', 'function': 'some_function'}
I want to do some pre-check of the dict to ensure that 'field' always exists, and that no more keys exist beyond 'group' and 'function' which are both optional.
I know I can do this by using a long and untidy if statement, but I'm thinking there must be a cleaner way?
This is what I currently have:
if (('field' in dict_name and len(dict_name.keys()) == 1) or ('group' in dict_name and len(dict_name.keys()) == 2) or ('function' in dict_name and len(dict_name.keys()) == 2) or ('group' in dict_name and 'function' in dict_name and len(dict_name.keys()) == 3))
Essentially I'm first checking if 'field' exists as this is required. I'm then checking to see if it is the only key (which is fine) or if it is a key alongside 'group' and no others, or a key alongside 'function' and no others or a key alongside both 'group' and 'function' and no others.
Is there a tidier way of checking the keys supplied are only these 3 keys where two are optional?
How do you check if a key exists or not in a dictionary? You can check if a key exists or not in a dictionary using if-in statement/in operator, get(), keys(), handling 'KeyError' exception, and in versions older than Python 3, using has_key(). 2.
The “in” Keyword When querying a dictionary, the keys, and not the values, are searched.
Method 1: Add new keys using the Subscript notation This method will create a new key\value pair on a dictionary by assigning a value to that key. If the key doesn't exist, it will be added and will point to that value. If the key exists, the current value it points to will be overwritten.
As far as I'm concerned you want to check, that
{'field'}
is always contained in the set of your dict keys{'field', 'group', 'function'}
So just code it!
required_fields = {'field'} allowed_fields = required_fields | {'group', 'function'} d = {'field': 123} # Set any value here if required_fields <= d.keys() <= allowed_fields: print("Yes!") else: print("No!")
This solution is scalable for any sets of required and allowed fields unless you have some special conditions (for example, mutually exclusive keys)
(thanks to @Duncan for a very elegant code reduction)
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