Use dict.items() to Iterate
ID |
python.use_items_iterate_dict |
Severity |
info |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Best Practice |
Language |
Python |
Tags |
best-practice, code-style |
Description
Reports for k in d: loops whose body indexes the same dict by the key (d[k]). The Python idiom is for k, v in d.items():, which avoids the per-iteration lookup and reads more clearly.
for key in mapping:
value = mapping[key] # FLAW
do(key, value)
for key, value in mapping.items(): # OK
do(key, value)
Rationale
d[k] does a hash lookup every iteration; d.items() yields the values directly. The performance difference is small but consistent, and the items() form is the canonical "I am iterating this dict" signal — readers do not have to check the body to know whether you wanted keys, values, or both.
Remediation
for key, value in mapping.items():
process(key, value)
# When you only need the values:
for value in mapping.values():
process(value)