Skip to content

in-dict-keys

Pythonstyleno fixdefault: offpython/ruff

Reports a membership test, a for loop or a comprehension over .keys() with no arguments, as in k in d.keys().

A dict tests membership and iterates its keys by itself. .keys() adds a call, and for a membership test it makes a view first, which is slower than the test on the dict.

To fix, drop .keys().

Reported
a = b = c = d = k = 1
x = k in d.keys()
x = k not in d.keys()
x = k in d.keys(1)
x = [k for k in d.keys()]
for k in d.keys():
pass
...
After the fix
a = b = c = d = k = 1
x = k in d.keys()
x = k not in d.keys()
x = k in d.keys(1)
x = [k for k in d.keys()]
for k in d.keys():
pass
...
python:
lint:
rules:
in-dict-keys: warn # off (default), warn, error

Enabled by the presets: python/ruff.

Suppress one line with sudsy-disable-next-line in-dict-keys in a comment of the file’s language.

The same check in other tools; Sudsy reports what each upstream rule reports.

Tool Rule Match
ruff SIM118 full