Last active
December 14, 2015 15:38
-
-
Save Velrok/5108780 to your computer and use it in GitHub Desktop.
Taming all the trees.
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 traverse_dict(node, leaf_fn, node_fn=lambda v, path: None, path=tuple()): | |
for k, v in node.iteritems(): | |
current_path = path + tuple([k]) | |
if isinstance(v, dict): | |
node_fn(v, current_path) | |
traverse_dict(v, leaf_fn, node_fn, current_path) | |
elif isinstance(v, list): | |
current_path = current_path + tuple(["[*]"]) | |
for i in v: | |
if isinstance(i, dict): | |
node_fn(i, current_path) | |
traverse_dict(i, leaf_fn, node_fn, current_path) | |
else: | |
leaf_fn(i, current_path) | |
else: | |
leaf_fn(v, current_path) |
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 test_traverse_dict_handles_dicts_as_values(): | |
d = {"a": {"bc": 0}} | |
def test_fn(value, path): | |
eq_(value, 0) | |
eq_(path, ("a", "bc")) | |
traverse_dict(d, test_fn) | |
def test_traverse_dict_handles_lists_of_dicts(): | |
d = {"a": [{"b": 1}, {"b": 2}]} | |
def test_fn(value, path): | |
assert(value == 1 or value == 2) | |
eq_(path, ("a", "[*]", "b")) | |
traverse_dict(d, test_fn) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment