Skip to content

Instantly share code, notes, and snippets.

@Flushot
Created April 2, 2015 07:24
Show Gist options
  • Select an option

  • Save Flushot/1a28c201a056efce6814 to your computer and use it in GitHub Desktop.

Select an option

Save Flushot/1a28c201a056efce6814 to your computer and use it in GitHub Desktop.
def dfs_visit_key(tree, key_re, visitor_fn):
return dfs_walk(tree, \
lambda k, fk, val: \
visitor_fn(fk, val) \
if re.match(key_re, '.'.join(fk)) \
else val)
def dfs_walk(tree, visitor_fn, fullkey=None):
fullkey = list(fullkey or [])
if isinstance(tree, dict): # subtree
return dict([(k, dfs_walk(v, visitor_fn, fullkey + [k])) \
for k, v in tree.iteritems()])
else: # leaf
k = fullkey[-1] if len(fullkey) else None
return visitor_fn(k, fullkey, tree)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment