python SyntaxError with dict(1=...), but {1:...} works

abalter picture abalter · Apr 30, 2012 · Viewed 9k times · Source

Python seems to have an inconsistency in what kind of keys it will accept for dicts. Or, put another way, it allows certain kinds of keys in one way of defining dicts, but not in others:

>>> d = {1:"one",2:2}
>>> d[1]
'one'
>>> e = dict(1="one",2=2)
  File "<stdin>", line 1
  SyntaxError: keyword can't be an expression

Is the {...} notation more fundamental, and dict(...) just syntactic sugar? Is it because there is simply no way for Python to parse dict(1="one")?

I'm curious...

Answer

Fred Foo picture Fred Foo · Apr 30, 2012

This is not a dict issue, but an artifact of Python syntax: keyword arguments must be valid identifiers, and 1 and 2 are not.

When you want to use anything that is not a string following Python identifier rules as a key, use the {} syntax. The constructor keyword argument syntax is just there for convenience in some special cases.