I often find myself needing to safely search a dictionary using get(), but return a default command. It'd be nice to have a version of dict_search_arg that returns a user-defined default instead of None. Or have 'default' added as an optional parameter to dict_search_arg.
This would cleanup a lot of code, and make a more consistent codebase when needing to search dictionaries but return default values.
Proposed change (or put into a new function):
def dict_search_args(dict_object, *path, default=None):
"""
Traverse dictionary using variable arguments.
Example: dict_search_args(some_dict, 'key', 'subkey', 'subsubkey', ..., default='N/A')
"""
if not isinstance(dict_object, dict) or not path:
return default
for item in path:
if not isinstance(dict_object, dict) or item not in dict_object:
return default
dict_object = dict_object[item]
return dict_objectNOTE: Sorry if this already exists, I couldn't find any existing helper function that did it.