Sep-17-2020, 01:29 PM
Hello,
I'm using xmltodict to work with XML files. It turns data into nested dictionaries.
In nested dictionaries that don't contain the same keys, I can't find an easy way to simply check if any given key exists somewhere.
The following functions don't work as expected:
Thank you.
I'm using xmltodict to work with XML files. It turns data into nested dictionaries.
In nested dictionaries that don't contain the same keys, I can't find an easy way to simply check if any given key exists somewhere.
The following functions don't work as expected:
def f(d, keys): if not keys: return True return keys[0] in d and f(d[keys[0]], keys[1:]) def keys_exists(element, *keys): ''' Check if *keys (nested) exists in `element` (dict). ''' if not isinstance(element, dict): raise AttributeError('keys_exists() expects dict as first argument.') if len(keys) == 0: raise AttributeError('keys_exists() expects at least two arguments, one given.') _element = element for key in keys: try: _element = _element[key] except KeyError: return False return TrueIs there a way besides looping?
Thank you.