Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking dict keys to ensure a required key always exists, and that the dict has no other key names beyond a defined set of names

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?

like image 407
nimgwfc Avatar asked Sep 29 '20 11:09

nimgwfc


People also ask

How do you check if a key is present in dict or not?

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.

What is the keyword that is used to check if a particular key exists in a dictionary?

The “in” Keyword When querying a dictionary, the keys, and not the values, are searched.

Which method will add a key to the dictionary if it does not already exist in the dictionary?

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.


1 Answers

As far as I'm concerned you want to check, that

  1. The set {'field'} is always contained in the set of your dict keys
  2. The set of your dict keys is always contained in the set {'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)

like image 135
Kolay.Ne Avatar answered Oct 02 '22 06:10

Kolay.Ne