python递归删除dict键[重复]

zpgglvta  于 2023-01-14  发布在  Python
关注(0)|答案(1)|浏览(144)
    • 此问题在此处已有答案**:

How to avoid "RuntimeError: dictionary changed size during iteration" error?(14个答案)
2天前关闭。
我想从嵌套dict中删除空dict

input = ss = {"a":"12","b":{"f":"34","z":{}}}

def recurfun(dict_data):
    for key,values in ss.items():
        if isinstance(values, dict) and values == {}:
            del ss[key]
        if isinstance(values, dict):
            recurfun(values)
    return ss
recurfun(ss)

错误消息为"迭代期间字典大小发生变化"

output_should_be = {"a":"12","b":{"f":"34"}}
rseugnpd

rseugnpd1#

您可以使用dict解析和if子句来构建新的dict,以过滤掉空dict的值,而不是就地删除键:

def recurfun(d):
    return {k: recurfun(v) if isinstance(v, dict) else v for k, v in d.items() if v != {}}

演示:https://replit.com/@blhsing/SelfreliantWonderfulBlogware

相关问题