The Python Oracle

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

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Track title: CC B Schuberts Piano Sonata No 16 D

--

Chapters
00:00 Question
01:26 Accepted answer (Score 266)
02:07 Answer 2 (Score 22)
02:29 Answer 3 (Score 11)
03:04 Answer 4 (Score 0)
03:50 Thank you

--

Full question
https://stackoverflow.com/questions/8406...

Question links:
[differences between "d = dict()" and "d = {}"]: https://stackoverflow.com/questions/2745...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #pycharm

#avk47



ACCEPTED ANSWER

Score 269


What is the code following 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}

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

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



ANSWER 2

Score 23


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"



ANSWER 3

Score 12


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




ANSWER 4

Score 0


mydict = {
  a: 5,
  b:z+c/2
}

The dictionary could have been created directly without initialising them first and then reassigning new values.