我有一个由字典列表组成的复杂数据结构,这些字典进一步由字典列表组成。现在,我试图从内部嵌套的字典(从字典列表)中提取特定的key:value
对。希望下面的例子显示了我想要实现的
complex_data =
[[{'A': 'test1'},
{'A': 'test2'},
{'B': [{'C': {'testabc': {'A': 'xxx'}}},
{'C': {'test123': {'A': 'yyy'}, 'test456': {'A': '111abc'}}},
{'C': {'test123': {'A': 'yyy'}, 'test456': {'A': '111def'}}}]}],
.
.
[{'A': 'test11'},
{'A': 'test22'}],
.
.
[{'A': 'test33'},
{'A': 'test44'},
{'B': []}],
.
[{'A': 'test3'},
{'A': 'test4'},
{'B': [{'C': {'testabc': {'A': '111'}}},
{'C': {'test123': {'A': 'yyy'}, 'test456': {'A': '999abc'}}},
{'C': {'test123': {'A': 'yyy'}, 'test456': {'A': '999def'}}}]}]]
现在输出应该是字典的嵌套列表,如:
desired_output = [[{'A': 'test1'}, {'A': 'test2'}, 'test456': {'A': '111def'}],
.
.
[{'A': 'test3'}, {'A': 'test4'}, 'test456': {'A': '999def'}]]
我正在做
for y in complex_data:
desired_output.append([y[2]['B'][2]['C'] for y in row] for row in y)
但是这行不通。变量y
不会遍历列表B
。谁能让我知道这里的问题是什么以及如何解决它?我用的是python3.9
更新:在某些情况下,完整列表B
可能缺失或可能为空{'B': []}
。
提前感谢。
p。S:如果有遗漏或不清楚的地方,请告诉我。
这里的主要思想是将dictionary转换为dataframe, dataframe通过行添加到新列表
代码:
步骤1:
df = pd.json_normalize(complex_data )
df[2] = df[2].apply(lambda x: {k:v for k , v in dict(map(dict.popitem, x['B']))['C'].items() if k=='test456'})
df
#输出0 1 2
0 {'A': 'test1'} {'A': 'test2'} {'test456': {'A': '111def'}}
1 {'A': 'test3'} {'A': 'test4'} {'test456': {'A': '999def'}}
步骤2:
desired_output = df.values.tolist()
desired_output
#输出[[{'A': 'test1'}, {'A': 'test2'}, {'test456': {'A': '111def'}}],
[{'A': 'test3'}, {'A': 'test4'}, {'test456': {'A': '999def'}}]]
你可以使用if..else.来避免None或{}值。如下:
df[2].apply(lambda x: {} if len(x['B'])==0 else({} if not x['B'][-1] else ({'test456':x['B'][-1]['C']['test456']} if 'test456' in x['B'][-1]['C'].keys() else {})))