抱歉愚蠢的问题,但我做错了什么?
我有嵌套的dict,我希望将其转储到json中。
[{'text': 'Root', 'children': [{'text': 'X', 'children': [None, None], 'id': 2}, {'text': 'Y', 'children': [], 'id': 3}], 'id': 1}]
我需要删除所有'无'来自它的价值观。这是我的代码:
for items in sub_tree_dicts:
del_null(items['children'])
def del_null(childrens):
for child in childrens:
if child is None:
childrens.remove(child)
else:
del_null(child['children'])
不幸的是,代码无法按预期工作,只删除了第一个“无”代码。从列表中。我哪里错了?
感谢名单。
答案 0 :(得分:0)
当您在列表上进行迭代时,不应修改字典/列表/等。你可以打破引用,这样循环就不知道去哪了。
我相当确定有一种更好的方法,但是如果我不做太多修改你的代码就会这样做:
for items in sub_tree_dicts:
del_null(items['children'])
def del_null(childrens):
invalid_children = []
for child in childrens:
if child is None:
invalid_children.append(child)
else:
del_null(child['children'])
for child in invalid_children:
childrens.remove(child)
答案 1 :(得分:0)
你可以试试这个:
s = [{'text': 'Root', 'children': [{'text': 'X', 'children': [None, None], 'id': 2}, {'text': 'Y', 'children': [], 'id': 3}], 'id': 1}]
d = {}
def filter_none(s, last=None):
if last:
new_list = [{a:[i for i in b if i is not None] if isinstance(b, list) else b for a, b in c.items()} for c in s]
return new_list
for a, b in s.items():
if not isinstance(b, list):
d[a] = b
else:
d[a] = filter_none(b, last=a)
filter_none(s[0])
new_d = [d]
输出:
[{'text': 'Root', 'children': [{'text': 'X', 'children': [], 'id': 2}, {'text': 'Y', 'children': [], 'id': 3}], 'id': 1}]