Created
March 17, 2016 01:57
-
-
Save abcdabcd987/90247e7cad17ba8fa348 to your computer and use it in GitHub Desktop.
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 flatEnumerate(obj, prefix='root'): | |
if isinstance(obj, int): | |
return [{ prefix: obj }] | |
elif isinstance(obj, list): | |
res = [] | |
for option in obj: | |
res.extend(flatEnumerate(option, prefix)) | |
return res | |
elif isinstance(obj, dict): | |
if len(obj) == 0: return [{}] | |
key = next(iter(obj.keys())) | |
value = obj.pop(key) | |
cur = flatEnumerate(value, '{0}.{1}'.format(prefix, key)) | |
rest = flatEnumerate(obj, prefix) | |
res = [] | |
for x in cur: | |
for y in rest: | |
d = y.copy() | |
d.update(x) | |
res.append(d) | |
return res | |
else: | |
raise TypeError('blah') | |
def pprint(l): | |
for e in l: print(e) | |
print() | |
A = 1 | |
pprint(flatEnumerate(A)) | |
B = [1, 2] | |
pprint(flatEnumerate(B)) | |
C = { | |
'a1': [0, 1], | |
'a2': { | |
'b1': [10, { 'c1': 20, 'c2': 21 }, 12], | |
'b2': 13 | |
}, | |
'a3': [ | |
{ 'b3': 14, 'b4': 15 }, | |
{ 'b5': 16, 'b6': 17 } | |
] | |
} | |
pprint(flatEnumerate(C)) | |
# output: | |
# {'root': 1} | |
# | |
# {'root': 1} | |
# {'root': 2} | |
# | |
# {'root.a3.b3': 14, 'root.a3.b4': 15, 'root.a2.b2': 13, 'root.a2.b1': 10, 'root.a1': 0} | |
# {'root.a1': 0, 'root.a3.b6': 17, 'root.a2.b2': 13, 'root.a3.b5': 16, 'root.a2.b1': 10} | |
# {'root.a3.b3': 14, 'root.a3.b4': 15, 'root.a2.b2': 13, 'root.a2.b1': 10, 'root.a1': 1} | |
# {'root.a1': 1, 'root.a3.b6': 17, 'root.a2.b2': 13, 'root.a3.b5': 16, 'root.a2.b1': 10} | |
# {'root.a2.b1.c1': 20, 'root.a2.b2': 13, 'root.a2.b1.c2': 21, 'root.a1': 0, 'root.a3.b4': 15, 'root.a3.b3': 14} | |
# {'root.a2.b1.c1': 20, 'root.a2.b2': 13, 'root.a2.b1.c2': 21, 'root.a3.b5': 16, 'root.a1': 0, 'root.a3.b6': 17} | |
# {'root.a2.b1.c1': 20, 'root.a2.b2': 13, 'root.a2.b1.c2': 21, 'root.a1': 1, 'root.a3.b4': 15, 'root.a3.b3': 14} | |
# {'root.a2.b1.c1': 20, 'root.a2.b2': 13, 'root.a2.b1.c2': 21, 'root.a3.b5': 16, 'root.a1': 1, 'root.a3.b6': 17} | |
# {'root.a3.b3': 14, 'root.a3.b4': 15, 'root.a2.b2': 13, 'root.a2.b1': 12, 'root.a1': 0} | |
# {'root.a1': 0, 'root.a3.b6': 17, 'root.a2.b2': 13, 'root.a3.b5': 16, 'root.a2.b1': 12} | |
# {'root.a3.b3': 14, 'root.a3.b4': 15, 'root.a2.b2': 13, 'root.a2.b1': 12, 'root.a1': 1} | |
# {'root.a1': 1, 'root.a3.b6': 17, 'root.a2.b2': 13, 'root.a3.b5': 16, 'root.a2.b1': 12} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment