SurpriseDog
SurpriseDog

Reputation: 484

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?

Upvotes: 1

Views: 884

Answers (3)

Barmar
Barmar

Reputation: 781706

Dictionary keys are strings, there are no forbidden values.

But there are reserved words that can't be used as variables, so you can't use that syntax for creating the dictionary if any of the keys are reserved words. as is reserved for its use in the with statement.

Instead, use a dictionary literal.

d = {'ys': 1e-24, 'zeptoseconds': 1e-21, 'zs': 1e-21, 'attoseconds': 1e-18, 'as':1e-18}

Upvotes: 2

wim
wim

Reputation: 363053

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

Upvotes: 2

Jay Mody
Jay Mody

Reputation: 4053

as is a reserved word in python.

>>> as = 10
  File "<stdin>", line 1
    as = 10
     ^
SyntaxError: invalid syntax

However, it is possible to use it as a dict key like so:

d = {"as": 10}

If you're curious where as shows up in python:

import json.load as loadjson

with open("myinputfile.json", "r") as infile:
    data = loadjson(infile)

Upvotes: 2

Related Questions