跳到内容

dict-index-missing-items (PLC0206)

源自 Pylint 代码检查工具。

作用

检查字典迭代,这些迭代通过显式索引提取字典值,而不是使用 .items()

为什么这不好?

使用 .items() 迭代字典在语义上更清晰,并且比使用键提取值更有效率。

示例

ORCHESTRA = {
    "violin": "strings",
    "oboe": "woodwind",
    "tuba": "brass",
    "gong": "percussion",
}

for instrument in ORCHESTRA:
    print(f"{instrument}: {ORCHESTRA[instrument]}")

建议改为

ORCHESTRA = {
    "violin": "strings",
    "oboe": "woodwind",
    "tuba": "brass",
    "gong": "percussion",
}

for instrument, section in ORCHESTRA.items():
    print(f"{instrument}: {section}")