Skip to content

Instantly share code, notes, and snippets.

@mijorus
Last active May 5, 2022 07:54
Show Gist options
  • Save mijorus/f2193a454873484e2e77cdbbd643c6d2 to your computer and use it in GitHub Desktop.
Save mijorus/f2193a454873484e2e77cdbbd643c6d2 to your computer and use it in GitHub Desktop.
Python: search for a nested key in a dictionary but do not throw errors if the key does not exists (kinda like the ?? operator)
def key_in_dict(_dict: dict, key_lookup: str, separator='.'):
"""
Searches for a nested key in a dictionary and returns its value, or None if nothing was found.
key_lookup must be a string where each key is deparated by a given "separator" character, which by default is a dot
"""
if not isinstance(_dict, dict):
raise TypeError('First argument must be type Dict')
keys = key_lookup.split(separator)
subdict = _dict
for k in keys:
subdict = subdict[k] if (isinstance(subdict, dict) and k in subdict) else None
if subdict is None: break
return subdict
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment