Here is a function I used with some decision trees for language processing, it's not what you want, but it's the same basic idea.
def nodeMapForDict(d):
node_map = []
node_path = []
def nodeRecursiveMap(d, node_path):
for key, val in d.items():
if type(val) is not dict: node_map.append(node_path + [key])
if type(val) is dict:
nodeRecursiveMap(val, node_path + [key])
nodeRecursiveMap(d, node_path)
return node_map
And here is one that should fit your use case:
def flattenDict(d):
node_map = {}
node_path = []
def nodeRecursiveMap(d, node_path):
for key, val in d.items():
if type(val) is not dict: node_map['.'.join(node_path + [key])] = val
if type(val) is dict:
nodeRecursiveMap(val, node_path + [key])
nodeRecursiveMap(d, node_path)
return node_map
example:
d= {'d': [1, 2, 3, 4], 'e': {'b': {'c': 1}}, 'a': {'b': 'c'}}
In [49]: flattenDict(d)
Out[49]: {'d': [1, 2, 3, 4], 'e.b.c': 1, 'a.b': 'c'}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…