Created
April 2, 2015 07:24
-
-
Save Flushot/1a28c201a056efce6814 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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