我们说我们有以下内容......
pract={
"hello": {
"more": 1,
"some": 2,
"yes": [
{
"dicct": 1
},
{
"more_dict": 4
}
]
}
}
我有一个嵌入式dict/list
。我需要获得所有单一值。所以在这种情况下,我的结果将是......
[1, 2, 1, 4]
理想情况下,我想保留直接父母,所以这会更好......
[("more",1), ("some",2), ("dicct", 1), ("more_dict", 4)]
这是我的递归尝试......
def grab_children(father, result):
if type(father) == type([]):
for e in father:
if isinstance(e, dict):
grab_children(e, result)
else:
for child_key, child_value in father.items():
if isinstance(child_value, dict):
grab_children(child_value, result)
else:
result.append((child_key, child_value))
我这样跑...
child = []
grab_children(pract, child)
但是当我打印子数组时,我得到......
[('more', 1), ('some', 2), ('yes', [{'dicct': 1}, {'more_dict': 4}])]
显然不是我想要的输出。我的解决方案出了什么问题?
答案 0 :(得分:1)
def get_terminal_nodes(data):
if isinstance(data, list):
for item in data:
for i in get_terminal_nodes(item):
yield i
elif isinstance(data, dict):
for k, item in data.items():
if isinstance(item, (list, dict)):
for i in get_terminal_nodes(item):
yield i
else:
yield k, item
pract = {
"hello": {
"more": 1,
"some": 2,
"yes": [{"dicct": 1}, {"more_dict": 4}]}
}
flat_data = dict(get_terminal_nodes(pract))
print(flat_data)
{'more': 1, 'some': 2, 'dicct': 1, 'more_dict': 4}