In short I am using a Yaml file as a configuration for parameters of some pipelines / functions I am using. In python, this is a nested dictionary, and parameters can themselves be an array / dictionaries. It would be helpful to iterate through all of the configuration files and search for those a subset of values are specified e.g.
# toy example of all parameters a config file might have
- param_a: 1
- param_b:
- b1: 'a'
- b2: [1,2,3]
# want all configs with these values
- param_a: 1
- param_b:
- b2: [1,2,3]
Of course one could do recursion on each nested dictionary, but rather than reinvent the wheel, I was wondering if there is a tried and true solution.
I have seen some related questions (looking to confirm identical dictionaries) and Deep Diff pops up. However, it is unclear if when testing a subset, DeepDiff will return all of the missing keys. Thoughts?
For now I am using this and assuming yaml has been loaded properly as a nested dictionary
def is_config_subset(truth, params):
'''
Arguments:
----------
truth (dict): dictionary of parameters to compare to
params (dict): dictionary of parameters to test
Returns:
----------
result (bool) whether or not `params` is a subset of `truth`
'''
if not type(truth) == type(params): return False
for key, val in params.items():
if key not in truth: return False
if type(val) is dict:
if not is_config_subset(truth[key], val):
return False
else:
if not truth[key] == val: return False
return True
print(is_config_subset({'a':1, 'b':2}, {'b':2}))
print(is_config_subset({'a':1, 'b':2}, {'b':2, 'c':3}))
print(is_config_subset({'a':1, 'b':2, 'c':[1,2,3]}, {'b':2, 'c':[1,2,3]}))
print(is_config_subset({'a':1, 'b':2, 'c':[1,2,3]}, {'b':2, 'c':[1,2]}))
print(is_config_subset({'a':1, 'b':2, 'c':[1,2,3]}, {'a':2, 'b':2}))
True
False
True
False
False
This is probably a simplistic example and will not work in all cases.