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

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)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)