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

Chris Sears picture Chris Sears · Dec 6, 2011 · Viewed 83.4k times · Source

When initializing a dictionary with d = {} Pycharm's code inspector generates a warning, saying

This dictionary creation could be rewritten as a dictionary literal.

If I rewrite it d = dict() the warning goes away. Since {} already is a dictionary literal, I'm pretty sure the message is erroneous. Furthermore, it seems like both d = {} and d = dict() are valid and Pythonic.

This related question seems to conclude that the choice is just a matter of style/preference: differences between "d = dict()" and "d = {}"

Why would Pycharm complain about d = {}?

UPDATE:

Mac nailed it. The warning actually applied to multiple lines, not just the one that was flagged.

Pycharm seems to look for a sequence of consecutive statements where you initialize a dictionary and then set values in the dictionary. For example, this will trigger the warning:

d = {}
d['a'] = 1

But this code will not:

d = {}
pass
d['a'] = 1

Answer

mac picture mac · Dec 6, 2011

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!