0

from collections.abc import Mapping
def access_keys(dic):
    print("Checking keys: ",list(dic.keys()))
    
    if len(list(dic.keys()))==0:
        print("No key found:")
        return 
    
    for key , value in dic.items():
        
        if isinstance(dic.get(key, None), Mapping):
            #print(f"{key}:{value}")
            new_dic = json.dumps(dic.get(key), indent=2)
            print(key,new_dic)
            print(f"{'_'*20}\n{'_'*20}\n")
            return access_keys(dic.get(key, None))
            print(f"key:{key}")
            print(f"value:{value}")
        
        else:
            print("None dic got",f"{key}:{dic[key]}")
        
        print(dic.get(key))

I want to access every key in a dic but Recursion is ending after getting an empty list of keys, I m not sure what is missing in this.

Please help me to solve this problem, also descibe me what is wrong with this code.

Willeke
  • 14,578
  • 4
  • 19
  • 47
  • You have a return in your for loop so the function ends after the first iteration. Your function doesn't apear to return anything so just removing the `return` should solve it. – Roy Cohen May 25 '21 at 15:55
  • 3
    Does this answer your question? [Access nested dictionary items via a list of keys?](https://stackoverflow.com/questions/14692690/access-nested-dictionary-items-via-a-list-of-keys) – 8349697 May 25 '21 at 15:58
  • Provide an example for `dic` – aneroid May 25 '21 at 16:18
  • See also https://stackoverflow.com/questions/10756427/loop-through-all-nested-dictionary-values – 8349697 May 25 '21 at 17:11
  • Thanks 'Roy Cohen' and others, i found the problem in the code, it was just a return statement at the wrong place. Now I have solved the problem thanks to Roy. – Manish kumar MoNi May 26 '21 at 03:44

0 Answers0