Last active
January 18, 2024 05:33
-
-
Save douglasmiranda/5127251 to your computer and use it in GitHub Desktop.
Find all occurences of a key in nested python dictionaries and lists - http://stackoverflow.com/questions/9807634/find-all-occurences-of-a-key-in-nested-python-dictionaries-and-lists
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
# This is a really old post, in the comments (and stackoverflow too) you'll find better solutions. | |
def find(key, dictionary): | |
for k, v in dictionary.iteritems(): | |
if k == key: | |
yield v | |
elif isinstance(v, dict): | |
for result in find(key, v): | |
yield result | |
elif isinstance(v, list): | |
for d in v: | |
for result in find(key, d): | |
yield result | |
example = {'app_url': '', 'models': [{'perms': {'add': True, 'change': True, 'delete': True}, 'add_url': '/admin/cms/news/add/', 'admin_url': '/admin/cms/news/', 'name': ''}], 'has_module_perms': True, 'name': u'CMS'} | |
list(find('admin_url', example)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for the help.
Python3 users should replace dictionary.iteritems() with dictionary.items(). iteritems was removed.