0
dct = {'global': {'bar': {'bar1': {'bar2': {}}, 'b': 1, 'zoo': {}}}}
answers = []
# open dictionary that contains 'arg' among key
def get_d(d, arg):
    for key in d:
        if key == arg:
            return d
        elif isinstance(d[key], dict) and d[key] != {}:
            answers.append(get_d(d[key], arg))

get_d(dct, 'zoo')
print(answers) # [None, {'bar1': {'bar2': {}}, 'b': 1, 'zoo': {}}, None]

But I want the function to return only that dict, without using a list.

# If you change 'answers.append(get_d(d[key], arg))' 
# on 'return get_d(d[key], arg)' result of call would be None

The answer I expect is:

# {'bar1': {'bar2': {}}, 'b': 1, 'zoo': {}}
Wes Hardaker
  • 21,735
  • 2
  • 38
  • 69
Ilya
  • 13
  • 3
  • Can you please elaborate more, or perhaps tell your expected output –  Jun 26 '21 at 13:44
  • 1
    Does this answer your question? [Loop through all nested dictionary values?](https://stackoverflow.com/questions/10756427/loop-through-all-nested-dictionary-values) – crissal Jun 26 '21 at 13:46
  • @Sujay Expected output of get_d(dct, 'zoo') is {'bar1': {'bar2': {}}, 'b': 1, 'zoo': {}}. But in summary it returns list with right answer and couple of Nones. If I don't use list to save recursions output, it returns only None but I want that recursion to return only right answer – Ilya Jun 26 '21 at 13:47
  • Ah, so you would like to get the complete dictionaries below the top level that contain the `arg`. And for the case of multiple matches? Should it return a list of dictionaries? – Dr. V Jun 26 '21 at 13:53
  • @crissal in that post he needs print out value but I trying to figure out how to make a proper return of value – Ilya Jun 26 '21 at 13:54
  • @Dr.V list there is only for illustrative purpose. By design should be only one match. – Ilya Jun 26 '21 at 13:57

0 Answers0