【发布时间】:2019-02-04 11:38:07
【问题描述】:
我正在处理一个复杂的嵌套字典和列表数据结构。我需要展平数据并将所有嵌套项置于 0 级。请参阅下面的示例以获得更清晰的信息:
{a:1,b:2,c:{c1:[{c11:1,c12:2,c13:3},{c21:1,c22:2,c23:3}],d1:[{d11:1,d12:2,d13:3},{d21:1,d22:2,d23:3}]},x:1,y:2}
我需要将其展平为:
{a:1,b:2,c_c1_c11:1, c_c1_c12:2,c_c1_c13:3,c_c1_c21:1,c_c1_c22:2,c_c1_c23:3, c_d1,d11:1...and so on}
我参考了this post 中的第一个答案,但它只有在我有嵌套字典时才能工作,而不是当列表嵌套在字典中并且更多字典嵌套在这些列表中时。
我稍微修改了代码以适应我的用例,但是这段代码不起作用
def flattenDict(d):
node_map = {}
node_path = []
def nodeRecursiveMap(d, node_path):
for key, val in d.items():
if ((type(val) is not dict)&(type(val) is not list)):
node_map['_'.join(node_path + [key])] = val
if type(val) is list:
def nodeListRecursion(val,node_path):
for element in val:
if ((type(element) is not dict)&(type(element) is not list)) : node_map['_'.join(node_path + [key])] = element
if type(element) is list: nodeListRecursion(element,node_map)
if type(element) is dict: nodeRecursiveMap(element, node_path + [key])
nodeListRecursion(val,node_path)
if type(val) is dict: nodeRecursiveMap(val, node_path + [key])
nodeRecursiveMap(d, node_path)
return node_map
当我将代码粘贴到此处时,缩进变得混乱。但我真的很感激这里的任何帮助。
【问题讨论】:
标签: python list dictionary nested flatten