Not a member of Pastebin yet?
                        Sign Up,
                        it unlocks many cool features!                    
                - ## for finding the keys and/or indices on the path to a target variable in a nested data structure ###
 - ## example usage at https://stackoverflow.com/a/76448138/6146136 ##########
 - def yield_key_paths(objC, valT, kPath=None, validTypes=(tuple,list,dict,set)):
 - ''' Traverse objC data structure recursively to yield path/s to valT'''
 - if not isinstance(kPath, list): kPath = []
 - if objC == valT: yield kPath
 - if not isinstance(objC, validTypes): return
 - for k,v in (objC.items() if isinstance(objC,dict) else enumerate(objC)):
 - yield from yield_key_paths(v, valT, kPath+[k], validTypes)
 - def find_nested_val(obj, val, findAll=False, validTypes=(tuple,list,dict,set)):
 - '''Get a list of or the first path to val in obj (No path -> [] or None)'''
 - paths = yield_key_paths(obj, val, [], validTypes)
 - return list(paths) if findAll else next(paths, None)
 
Advertisement
 
                    Add Comment                
                
                        Please, Sign In to add comment