Try95th

find_nested_val

Jun 10th, 2023
161
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.92 KB | None | 0 0
  1. ## for finding the keys and/or indices on the path to a target variable in a nested data structure ###
  2. ## example usage at https://stackoverflow.com/a/76448138/6146136                            ##########
  3.  
  4.  
  5. def yield_key_paths(objC, valT, kPath=None, validTypes=(tuple,list,dict,set)):
  6.     ''' Traverse objC data structure recursively to yield path/s to valT'''
  7.     if not isinstance(kPath, list): kPath = []
  8.     if objC == valT: yield kPath
  9.  
  10.     if not isinstance(objC, validTypes): return
  11.     for k,v in (objC.items() if isinstance(objC,dict) else enumerate(objC)):
  12.         yield from yield_key_paths(v, valT, kPath+[k], validTypes)
  13.  
  14.        
  15. def find_nested_val(obj, val, findAll=False, validTypes=(tuple,list,dict,set)):
  16.     '''Get a list of or the first path to val in obj (No path -> [] or None)'''
  17.     paths = yield_key_paths(obj, val, [], validTypes)
  18.     return list(paths) if findAll else next(paths, None)  
  19.  
Advertisement
Add Comment
Please, Sign In to add comment