如何修复 pylint 错误“不必要使用理解”

Ale*_*lex 8 python pylint python-3.x

使用 python 3.8.6 和 pylint 2.4.4 以下代码会产生 pylint 错误(或建议)

R1721: Unnecessary use of a comprehension (unnecessary-comprehension)
Run Code Online (Sandbox Code Playgroud)

这是代码:

dict1 = {
    "A": "This is A",
    "B": "This is B"
}
bools = [True, False]

dict2 = {key: value for key, value in zip(dict1.keys(), bools)}
Run Code Online (Sandbox Code Playgroud)

如何修复代码以消除此 R1721 消息?

kay*_*ya3 8

构造dict函数采用可迭代的键/值对,因此正如消息所述,这里不需要字典理解。

dict2 = dict(zip(dict1.keys(), bools))
Run Code Online (Sandbox Code Playgroud)

  • 我认为你甚至可以做`dict(zip(dict1, bools))`,因为默认情况下迭代字典会迭代键,不是吗? (2认同)