Skip to content

Rule suggestion: recommend dict.fromkeys over comprehension #9592

@tjkuson

Description

@tjkuson

Replace

{elt: None for elt in foo}

with

dict.fromkeys(foo)

dict.fromkeys is more efficient and readable.

In [4]: import random

In [5]: choices = ("red", "green", "blue")

In [6]: dupes = [random.choice(choices) for _ in range(1000)]

In [7]: %timeit list({elt: None for elt in dupes})
18.8 µs ± 97.8 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each)

In [8]: %timeit list(dict.fromkeys(dupes))
12.6 µs ± 49.9 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each)

Efficiency boost tested on both Python 3.9 and 3.12.

Note: would have to skip this rule for mutable values (see #4613).

Metadata

Metadata

Assignees

No one assigned

    Labels

    acceptedReady for implementationruleImplementing or modifying a lint rule

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions