Skip to content
Advertisement

Are certain words forbidden as keys in a dict() statement?

So I was getting carried away after finishing my function to convert user time strings to seconds when I decided to extend my conversion dictionary with the statement:

dict(ys=1e-24, zeptoseconds=1e-21, zs=1e-21, attoseconds=1e-18, as=1e-18)

This fails. I can assign bs=1e-18, but if I assign as=1e-18 it says SyntaxError: invalid syntax, so I tried escaping the a but no luck.

Are there forbidden words in dictionary keys?

Advertisement

Answer

Are there forbidden words in dictionary keys?

No. You can use any string as a dictionary key.

>>> {"as": 1}
{'as': 1}

You just can’t use syntax keywords in the function call syntax because that will confuse the parser, and this is not specific to calling dict. You can not use the following strings as keywords in any function call:

>>> import keyword
>>> for kw in keyword.kwlist:
...     print(kw)
... 
False
None
True
__peg_parser__
and
as
assert
async
await
break
class
continue
def
del
elif
else
except
finally
for
from
global
if
import
in
is
lambda
nonlocal
not
or
pass
raise
return
try
while
with
yield
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement