Skip to content

Instantly share code, notes, and snippets.

@Velrok
Last active December 14, 2015 15:38
Show Gist options
  • Save Velrok/5108780 to your computer and use it in GitHub Desktop.
Save Velrok/5108780 to your computer and use it in GitHub Desktop.
Taming all the trees.
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)
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