Skip to content

Instantly share code, notes, and snippets.

@emblondel
Created October 13, 2022 07:50
Show Gist options
  • Save emblondel/32324e7bafe19aa87446cabda07e71f7 to your computer and use it in GitHub Desktop.
Save emblondel/32324e7bafe19aa87446cabda07e71f7 to your computer and use it in GitHub Desktop.
Returns an iterator that returns all key value pairs of a (nested) iterable.
def get_all_key_values(iterable, allow_sub_elements=False):
"""Returns an iterator that returns all key value pairs
of a (nested) iterable. If allow_subdict set to False,
will return only the subvalues, and not the nested dict
or list
Arguments:
- iterable: <list> or <dictionary>
- allow_subdict : boolean
Returns:
- <iterator>
"""
if isinstance(iterable, dict):
for key, value in iterable.items():
if allow_sub_elements:
yield (key, value)
else:
if not (isinstance(value, dict) or isinstance(value, list)):
yield (key,value)
else:
yield (key, None)
for ret in get_all_key_values(value, allow_sub_elements=allow_sub_elements):
yield ret
elif isinstance(iterable, list):
for el in iterable:
for ret in get_all_key_values(el, allow_sub_elements=allow_sub_elements):
yield ret
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment