I am looking to create a function that will check if multiple keys are present in a dictionary and return a value that indicates which keys were present. I know I could write something like:
def param_checker(parameters):
if 'foo' in parameters:
if 'bar' in parameters:
if 'qux' in parameters:
return 0
else:
return 1
elif 'baz' in parameters:
if 'qux' in parameters:
return 2
else:
return 3
else:
return 4
elif 'quxx' in parameters:
if 'bar' in parameters:
return 5
elif 'qux' in parameters:
if 'baz' in parameters:
return 6
else:
return 7
else:
return 8
else:
return 9
However, the above example is both messy and clunky. The complexity also scales with the number of parameters you need to check to return a value. For example, I needed 3 layers of if
conditions to check the keys foo
, bar
, and qux
. I know I could chain the if
conditions inline, but it is still messy and clunky.
This is somewhat similar to Python check if list of keys exist in dictionary. The big difference here is that instead of checking if they all exist or not, I am looking to return a value indicating what combination of keys exist.
Note: I did not write out all possible combinations in the provided sample code, as that would be tedious when I am just trying to illustrate the problem.
Below is a example of invoking the function to check which keys are present.
d = dict()
d['foo'] = 'blah'
d['bar'] = 'blah'
val = param_checker(d)
# val represents a unique value indicating which keys are present in dictionary d
I will know ahead of time what keys could be in the dictionary, so I can have some sort of list of possible keys, like:
keys = ["foo", "bar", "baz", "qux", "quxx"]
I am hoping to build a function that can check N
keys and return a unique value indicating which ones where present. How can I efficiently do this?