python SyntaxError与dict(1 = ...),但{1:...}的作品 [英] python SyntaxError with dict(1=...), but {1:...} works
问题描述
> >> d = {1:one,2:2}
>>>> d [1]
'one'
>>> e = dict(1 =one,2 = 2)
文件< stdin>,第1行
SyntaxError:关键字不能是表达式
{...}
符号更根本, dict(...)
只是语法糖?是不是因为Python没有办法解决这个问题(1 =one)?
'好奇...
这不是一个 dict
,但Python语法的工件:关键字参数必须是有效的标识符,而 1
和 2
不是。 p>
当您希望使用Python标识符规则作为关键字之后不是字符串的任何内容时,请使用 {}
语法。在某些特殊情况下,构造函数关键字参数语法就是方便。
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...
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.
这篇关于python SyntaxError与dict(1 = ...),但{1:...}的作品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!