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:
JavaScript
x
2
1
dict(ys=1e-24, zeptoseconds=1e-21, zs=1e-21, attoseconds=1e-18, as=1e-18)
2
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.
JavaScript
1
3
1
>>> {"as": 1}
2
{'as': 1}
3
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:
JavaScript
1
41
41
1
>>> import keyword
2
>>> for kw in keyword.kwlist:
3
print(kw)
4
5
False
6
None
7
True
8
__peg_parser__
9
and
10
as
11
assert
12
async
13
await
14
break
15
class
16
continue
17
def
18
del
19
elif
20
else
21
except
22
finally
23
for
24
from
25
global
26
if
27
import
28
in
29
is
30
lambda
31
nonlocal
32
not
33
or
34
pass
35
raise
36
return
37
try
38
while
39
with
40
yield
41