gpt4 book ai didi

python - 从嵌套字典中递归删除 None 值或 None 键

转载 作者:太空宇宙 更新时间:2023-11-04 11:08:35 30 4
gpt4 key购买 nike

问题:

如何遍历字典并从中删除 None 键或值?

这是我尝试过的:

代码:

import copy


def _ignore(data):
copied_data = copy.deepcopy(data)

print('-------------------------')
print(f'copied_data: {copied_data}')
print('-------------------------')

if isinstance(copied_data, list):
print(f'item is instance of list: {copied_data}')

for idx, item in enumerate(data):
if isinstance(item, list):
return _ignore(item)

elif isinstance(item, dict):
return _ignore(item)

elif item is None:
del copied_data[idx]

elif isinstance(copied_data, dict):
print(f'item is instance of dict: {copied_data}')

for key, item in data.items():
if isinstance(item, list):
return _ignore(item)

elif isinstance(item, dict):
return _ignore(item)

elif item is None:
del copied_data[key]

return copied_data


if __name__ == '__main__':
data = {'key1': None, 'key2': {'k1': None, 'k2': 2}, 'key3': [None, 1, 2, 3, 4]}

print(f'output: {_ignore(data=data)}')

输入:

{'key1': None, 'key2': {'k1': None, 'k2': 2}, 'key3': [None, 1, 2, 3, 4]}

输出:

-------------------------
copied_data: {'key1': None, 'key2': {'k1': None, 'k2': 2}, 'key3': [None, 1, 2, 3, 4]}
-------------------------
item is instance of dict: {'key1': None, 'key2': {'k1': None, 'k2': 2}, 'key3': [None, 1, 2, 3, 4]}
-------------------------
copied_data: {'k1': None, 'k2': 2}
-------------------------
item is instance of dict: {'k1': None, 'k2': 2}
output: {'k2': 2}

Keep in mind that the code also should remove None values in a nested list or nested dict and we can't remove an element from dict while we are iterating over it.

更新:代码应支持嵌套的 dictlist

这是另一个输入示例:

{'key1': None, None:1 ,'key2': {'k1': {'k3': [None, 1, 23], 'k4': None}, 'k2': 2},
'key3': [{'key1': None, 'key2': [None, 1, 2, 3], 'key3': {'k1': 1}}, 1, 2, 3, 4]}

谢谢。

最佳答案

你没有做你声称要做的事情,因为据我所知,你只是删除了 None 值。这个字典:

{'key1': None, 'key2': {'k1': None, 'k2': 2}, 'key3': [None, 1, 2, 3, 4]}

只有 None 值,没有键。我要在这里坚持键和值的 Python 定义。 None 键看起来像:

{None: "value"}

但是,您可以像这样轻松地做到这一点:

def recursive_filter(item, *forbidden):
if isinstance(item, list):
return [recursive_filter(entry, *forbidden) for entry in item if entry not in forbidden]
if isinstance(item, dict):
result = {}
for key, value in item.items():
value = recursive_filter(value, *forbidden)
if key not in forbidden and value not in forbidden:
result[key] = value
return result
return item

你可以这样使用:

clean = recursive_filter(dirty, None)

或者如果你想过滤掉更多:

clean = recursive_filter(dirty, *iterable_of_forbidden_things)
clean = recursive_filter(dirty, None, other_forbidden_thing)

如果你真的只关心值,那么你可以去掉对键的检查。

关于python - 从嵌套字典中递归删除 None 值或 None 键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58837293/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com