[英]Delete items from nested dict recursively
很抱歉这个愚蠢的问题,但是我在做什么错呢?
我已经嵌套了字典,希望将其转储到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'])
不幸的是,代码无法按预期工作,并且仅从列表中删除第一个“无”。 我哪里错了?
谢谢
遍历列表时,请勿修改字典/列表/等。 您可以中断引用,以便循环不知道要去哪里。
我相当确定这是一种更好的方法,但是无需过多修改您的代码就可以做到这一点:
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)
您可以尝试以下方法:
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}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.