This rule raises an issue when .keys() is called explicitly on a dictionary for membership testing.
In Python, dictionaries support direct membership testing without needing to explicitly call the .keys() method. When you write
key in dict.keys(), you are being unnecessarily verbose.
The expression key in dict is the idiomatic Python way to check for key membership. It is:
The .keys() method exists primarily for cases where you need to perform set operations on dictionary keys or when you need an explicit
view object. For simple membership testing, it is redundant because dictionaries are designed to support the in operator directly.
Unnecessarily verbose code patterns accumulate over a codebase and reduce readability. Following Python idioms makes code easier to review and maintain, and helps new contributors understand the codebase faster.
Remove the .keys() call and use direct membership testing on the dictionary. This is the standard Python idiom for checking if a key
exists in a dictionary.
my_dict = {'a': 1, 'b': 2, 'c': 3}
if 'a' in my_dict.keys(): # Noncompliant
print('Found')
my_dict = {'a': 1, 'b': 2, 'c': 3}
if 'a' in my_dict:
print('Found')