You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何使用items()方法改写字典遍历删除元素的代码

改写后的实现代码

for package, del_page_map in itemsToDelete.items():
    for page, del_items in del_page_map.items():
        # 可选的存在性校验,避免contents中无对应package或page时报KeyError,不需要可删除
        if package not in contents or page not in contents[package]:
            continue
        for item in del_items:
            if item in contents[package][page]:
                del contents[package][page][item]

改写说明

字典的items()方法会返回可遍历的(键, 值)元组序列,不需要在循环内再通过键重复索引原字典,符合pylint的规范要求,同时代码可读性更高。
上述代码完全保留了你原有逻辑,只是把通过键取值的步骤提前到循环声明阶段,执行效果和你原来的代码完全一致。

额外注意

你给出的示例字典存在语法问题:Python字典不允许同一个键重复声明,你示例中"page1": "item1"、"page1": "item2"等同名键重复赋值,最终只会保留最后一个赋值结果。如果你的实际业务是同一个页面下对应多个条目,建议将页面对应的值改为列表结构,比如"page1": ["item1", "item2", "item3"]。

内容的提问来源于stack exchange,提问作者Menryck

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 10:15:01