Last active
February 9, 2024 23:29
-
-
Save PatrikHlobil/9d045e43fe44df2d5fd8b570f9fd78cc to your computer and use it in GitHub Desktop.
Get all keys or values of a nested dictionary or list in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def iterate_all(iterable, returned="key"): | |
"""Returns an iterator that returns all keys or values | |
of a (nested) iterable. | |
Arguments: | |
- iterable: <list> or <dictionary> | |
- returned: <string> "key" or "value" | |
Returns: | |
- <iterator> | |
""" | |
if isinstance(iterable, dict): | |
for key, value in iterable.items(): | |
if returned == "key": | |
yield key | |
elif returned == "value": | |
if not (isinstance(value, dict) or isinstance(value, list)): | |
yield value | |
else: | |
raise ValueError("'returned' keyword only accepts 'key' or 'value'.") | |
for ret in iterate_all(value, returned=returned): | |
yield ret | |
elif isinstance(iterable, list): | |
for el in iterable: | |
for ret in iterate_all(el, returned=returned): | |
yield ret |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I used @mh-malekpour code and added support for objects that are nested inside of arrays.