Link to home
Start Free TrialLog in
Avatar of CalmSoul
CalmSoulFlag for United States of America

asked on

search dictionary in python

I am using following function to recursively search values in dictionary based on key.

I need assistance to change this and would like to pass a list of keys and search that recursively...

def get_recursively(search_dict, field):
    """Takes a dict with nested lists and dicts,
    and searches all dicts for a key of the field
    provided. This function recursively searches a dictionary 
    containing nested dictionaries and lists. It builds a list called 
    fields_found, which contains the value for every time the field is found.
    The 'field' is the key in the dictionary and its nested 
    lists and dictionaries.
    """
    fields_found = []

    for key, value in search_dict.items():

        if key == field:
            fields_found.append(value)

        elif isinstance(value, dict):
            results = get_recursively(value, field)
            for result in results:
                fields_found.append(result)

        elif isinstance(value, list):
            for item in value:
                if isinstance(item, dict):
                    more_results = get_recursively(item, field)
                    for another_result in more_results:
                        fields_found.append(another_result)

    return fields_found

Open in new window


Current usage

p=get_recursively(d,'id')
x=get_recursively(d,'title')

Open in new window


Required usage:

list=['id','title']
p=get_recursively(d,list)
print(p)

Open in new window

Avatar of boocko
boocko
Flag of Slovenia image

Change comparing operation in Line 14 from '==' to 'in'.

  if key in field:

Open in new window

This question needs an answer!
Become an EE member today
7 DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform.
View membership options
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.