Why does Pycharm's inspector complain about "d = {}"?

What is the following code to your dictionary declaration?

I think pycharm will trigger the error if you have something like:

dic = {}
dic['aaa'] = 5

as you could have written

dic = {'aaa': 5}

BTW: The fact that the error goes away if you use the function doesn't necessarily mean that pycharm believes dict() is a literal. It could just mean that it doesn't complain for:

dic = dict()
dic['aaa'] = 5

HTH!


This can be disabled in the Project Settings or Default Settings.

  • Navigate to Settings -> Inspections -> Python
  • Uncheck "Dictionary creation could be rewritten by dictionary literal"

for those who like (just like me) to initialize dictionaries with single operation

d = {
  'a': 12,
  'b': 'foo',
  'c': 'bar'
}

instead of many lines like

d = dict()
d['a'] = 12
d['b'] = ....

in the end I ended up with this:

d = dict()
d.update({
  'a': 12,
  'b': 'foo',
  'c': 'bar'
})

Pycharm is not complaining on this

Tags:

Python

Pycharm