- 此问题在此处已有答案**:
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"}}
1条答案
按热度按时间rseugnpd1#
您可以使用dict解析和
if
子句来构建新的dict,以过滤掉空dict的值,而不是就地删除键:演示:https://replit.com/@blhsing/SelfreliantWonderfulBlogware