跳到内容

dict-iter-missing-items (PLE1141)

预览(自 v0.3.0 起) · 相关问题 · 查看源码

源自 Pylint 代码检查工具。

修复总是可用的。

此规则不稳定且处于预览状态。使用需要 --preview 标志。

作用

检查 for 循环中是否存在未调用 .items() 的字典解包操作。

为什么这不好?

在 for 循环中遍历字典时,如果未调用 .items() 直接解包字典,若键不是包含两个元素的元组,可能会导致运行时错误。

您可能想要遍历的是 (键, 值) 对,这只有在调用 .items() 时才能实现。

示例

data = {"Paris": 2_165_423, "New York City": 8_804_190, "Tokyo": 13_988_129}

for city, population in data:
    print(f"{city} has population {population}.")

建议改为

data = {"Paris": 2_165_423, "New York City": 8_804_190, "Tokyo": 13_988_129}

for city, population in data.items():
    print(f"{city} has population {population}.")

已知问题

如果字典的键是一个元组,例如:

d = {(1, 2): 3, (3, 4): 5}
for x, y in d:
    print(x, y)

元组键会被解包到 xy 中,而不是对应键和值。这意味着建议使用的 d.items() 修复方案会导致不同的运行时行为。Ruff 无法一致地推断字典键的类型。

修复安全性

由于元组键存在的已知问题,此修复方案是不安全的。