SyntaxError:创建字典时,关键字不能是表达式 [英] SyntaxError: keyword can't be an expression while creating a dictionary
问题描述
我从cookie中检索了两个字符串
I got two strings retrieved from a cookie
name = 'rack.session'
val = 'CookieVal'
使用它们,我想建立一个字典
Using them I would like to build a dictionary
cookies = dict(rack.session=val)
但SyntaxError: keyword can't be an expression
所以我试图逃脱(.)点
So I tried to escape the (.) dot
re.escape(name)
...但是会引发相同的错误
... but it raises the same error
这怎么可能?根据Python的type()
名称是一个字符串:
How is this possible? According to Python type()
name is a string:
type(name)
<class 'str'>
为什么Python会混合字符串和表达式?
Why is Python mixing up strings and expressions?
推荐答案
rack.session
的问题是python认为您正在尝试使用表达式rack.session
的值并将其传递给dict()
,是不正确的,因为dict()
希望您在使用关键字参数时传递变量名,然后在创建dict时这些变量名就会转换为字符串.
The problem with rack.session
is that python thinks that you're trying to use the value of expression rack.session
and pass it to dict()
, which is incorrect because dict()
expects you to pass variables names when you're using keyword arguments, these variables name are then converted to strings when the dict is created.
简单的例子:
>>> dict('val' = 'a')
File "<ipython-input-21-1cdf9688c191>", line 1
SyntaxError: keyword can't be an expression
因此,您不能使用=
左侧的对象,而只能使用有效的标识符.
So, you can't use an object on the left side of =
, you can only use a valid identifier.
字节码使rack.session
会更清楚:
>>> import dis
>>> dis.dis(lambda : dict(rack.session , val))
1 0 LOAD_GLOBAL 0 (dict)
3 LOAD_GLOBAL 1 (rack) # load the object `rack`
6 LOAD_ATTR 2 (session)# use the value of it's attribute
# `session`
9 LOAD_GLOBAL 3 (val)
12 CALL_FUNCTION 2
15 RETURN_VALUE
因此,对于rack.session = val
,python会认为您正在尝试使用从rack.session
返回的值并将其传递给dict
,这是不正确的.其次,rack.session
不是有效的标识符,因为python标识符中不允许使用点(.
).
So, with rack.session = val
, python will think that you're trying to use the value returned from rack.session
and pass it to dict
, which is incorrect. Secondly rack.session
isn't a valid identifier as dots(.
) are not allowed in python identifiers.
这适用于python中的任何函数,甚至不包括dict
,关键字参数必须是有效的标识符.
This is applicable to any function in python not even dict
, a keyword argument must be a valid identifier.
来自文档:
keyword_item ::= identifier "=" expression
有效示例:
>>> dict(foo = 1, bar = '2')
{'foo': 1, 'bar': '2'}
对于您的示例,您只需执行以下操作即可:
For your example you can simply do:
>>> val = 'CookieVal'
>>> name = 'rack.session'
>>> dict(((name,val),))
{'rack.session': 'CookieVal'}
#or
>>> {name:val}
{'rack.session': 'CookieVal'}
这篇关于SyntaxError:创建字典时,关键字不能是表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!