Skip to content

Instantly share code, notes, and snippets.

@fungusakafungus
Last active December 31, 2015 22:49
Show Gist options
  • Save fungusakafungus/8055951 to your computer and use it in GitHub Desktop.
Save fungusakafungus/8055951 to your computer and use it in GitHub Desktop.
Prepend every substructure of a nested dict/list structure with its path
def prepend_with_path(j, path=''):
"""
>>> prepend_with_path({})
[('', {})]
>>> prepend_with_path([])
[('', [])]
>>> prepend_with_path({1:2})
[('', {1: 2}), ('[1]', 2)]
>>> prepend_with_path({'a':'b'})
[('', {'a': 'b'}), ("['a']", 'b')]
>>> prepend_with_path([1])
[('', [1]), ('[0]', 1)]
>>> prepend_with_path([{1:2}])
[('', [{1: 2}]), ('[0]', {1: 2}), ('[0][1]', 2)]
>>> prepend_with_path([0, {1:2}])
[('', [0, {1: 2}]), ('[0]', 0), ('[1]', {1: 2}), ('[1][1]', 2)]
"""
iterfuncs_by_type = {
dict: dict.iteritems,
list: enumerate,
}
res = [(path, j)]
type_of_j = type(j)
if type_of_j in iterfuncs_by_type:
for k, v in iterfuncs[type_of_j](j):
res += prepend_with_path(v, '%s[%r]' % (path, k))
return res
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment