This rule raises an issue when .items() is used to iterate over a dictionary and then either the key or the value is discarded.

Why is this an issue?

Using .items() to iterate over a dictionary and then discarding either the key or the value in each iteration is less efficient than directly iterating over only the keys or values needed.

Python dictionaries provide efficient ways to iterate over their contents:

for k in my_dict:
  ...

The .items() method is useful when you need both the key and the value within the loop. However, if your loop only uses the key, discarding the value, often with _, or only uses the value, discarding the key, calling .items() performs unnecessary work retrieving the part you don’t use.

While the performance difference might be minor for small dictionaries, using the more specific method is clearer, more idiomatic, and avoids retrieving and unpacking data that is immediately ignored, like`.keys()` for keys, or .values() for values.

How to fix it

Adjust the loop to use the most appropriate dictionary view method based on whether you need keys, values, or both: * If only values are needed, iterate over my_dict.values(). * If only keys are needed, iterate directly over the dictionary (for key in my_dict:) or use my_dict.keys(). * If both key and value are needed, continue using my_dict.items().

Code examples

Noncompliant code example

fruit = {'a': 'Apple', 'b': 'Banana'}
for _, value in fruit.items(): # Discards key
    print(value)
fruit = {'a': 'Apple', 'b': 'Banana'}
for key, _ in fruit.items(): # Discards value
    print(key)

Compliant solution

fruit = {'a': 'Apple', 'b': 'Banana'}
for value in fruit.values(): # Iterates only on values
    print(value)
fruit = {'a': 'Apple', 'b': 'Banana'}
for key in fruit: # Iterates directly over dictionary (yields keys)
    print(key)

Resources

Documentation