I made the below class.
class Message:
def __init__(self, message):
self.message = message
self.__dict__.update(message)
def dict_value_finder(self, field, partial_match=False):
"""It Takes a dict with nested lists and dicts,
and searches all dicts for a key of the field
provided and return the value(s) as a list.
set partial_match = True to get partial matches.
"""
fields_found = []
for key, value in self.message.items():
if field in key if partial_match else field == key:
fields_found.append(value)
print(key, value)
elif isinstance(value, dict):
results = dict_value_finder(value, field, partial_match)
fields_found.extend(results)
elif isinstance(value, list):
for item in value:
if isinstance(item, dict):
more_results = dict_value_finder(item, field,
partial_match)
fields_found.extend(more_results)
return fields_found
The function dict_value_finder would work outside the class as in:
def dict_value_finder(search_dict, field, partial_match=False):
"""Takes a dict with nested lists and dicts,
and searches all dicts for a key of the field
provided and return the value(s) as a list.
set partial_match = True to get partial matches.
"""
fields_found = []
for key, value in search_dict.items():
if field in key if partial_match else field == key:
fields_found.append(value)
print(key, value)
elif isinstance(value, dict):
results = dict_value_finder(value, field, partial_match)
fields_found.extend(results)
elif isinstance(value, list):
for item in value:
if isinstance(item, dict):
more_results = dict_value_finder(item, field,
partial_match)
fields_found.extend(more_results)
return fields_found
But when I put it inside the class I get the error:
File "<ipython-input-42-76ab838299bc>", line 23, in dict_value_finder
results = dict_value_finder(value, field, partial_match)
NameError: name 'dict_value_finder' is not defined
I'm not sure How to add this function to a class given that it needs recursion.
selfwhen referring tomessagebut not when referring todict_value_finder. Why?