Last active
December 31, 2015 22:49
-
-
Save fungusakafungus/8055951 to your computer and use it in GitHub Desktop.
Prepend every substructure of a nested dict/list structure with its path
This file contains 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 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