6

With python 3.8.6 and pylint 2.4.4 the following code produces a pylint error (or recommendation)

R1721: Unnecessary use of a comprehension (unnecessary-comprehension)

This is the code:

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

dict2 = {key: value for key, value in zip(dict1.keys(), bools)}

How can I fix the code to get rid of this R1721 message?

Alex
  • 41,580
  • 88
  • 260
  • 469

1 Answers1

7

The dict constructor takes an iterable of key/value pairs, so as the message says, a dict comprehension is unnecessary here.

dict2 = dict(zip(dict1.keys(), bools))
kaya3
  • 47,440
  • 4
  • 68
  • 97
  • 2
    I think you could even do `dict(zip(dict1, bools))`, since iterating over a dict iterates over the keys by default, no? – Paul M. Jan 26 '21 at 13:45
  • @PaulM. Yes; I think it's a matter of style whether you prefer to write `.keys()` to be more explicit. I personally don't. – kaya3 Jan 26 '21 at 14:01