Python在接受哪种键作为字典时似乎有一个不一致的地方。或者,换句话说,它允许某些类型的键以一种方式定义字典,但不允许以其他方式定义:
>>> 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是不是{...}表示法更基础,而dict(...)只是语法糖?是不是因为Python根本没有办法parse dict(1="one")
我很好奇..。
发布于 2012-05-01 05:10:45
这不是dict的问题,而是Python语法的缺陷:关键字参数必须是有效的标识符,而1和2不是。
当您希望使用任何不是遵循Python标识符规则的字符串作为键时,请使用{}语法。构造函数关键字参数语法只是为了在某些特殊情况下方便使用。
发布于 2012-05-01 05:11:05
dict是函数调用,函数关键字必须是标识符。
发布于 2016-10-05 00:34:52
正如其他答案所说,dict是一个函数调用。它有三种句法形式。
表单:
dict(**kwargs) -> new dictionary initialized with the name=value pairs
in the keyword argument list. For example: dict(one=1, two=2)键(或本例中使用的name )必须是有效的Python identifiers,int无效。
限制不仅仅是函数dict,你可以像这样演示它:
>>> def f(**kw): pass
...
>>> f(one=1) # this is OK
>>> f(1=one) # this is not
File "<stdin>", line 1
SyntaxError: keyword can't be an expression但是,您还可以使用另外两种语法形式。
有以下几点:
dict(iterable) -> new dictionary initialized as if via:
d = {}
for k, v in iterable:
d[k] = v示例:
>>> dict([(1,'one'),(2,2)])
{1: 'one', 2: 2}从一个映射中:
dict(mapping) -> new dictionary initialized from a mapping object's
(key, value) pairs示例:
>>> dict({1:'one',2:2})
{1: 'one', 2: 2}虽然这可能看起来不是很多(来自dict文本的字典),但请记住,Counter和defaultdict是映射,以下是如何将其中之一转换为dict:
>>> from collections import Counter
>>> Counter('aaaaabbbcdeffff')
Counter({'a': 5, 'f': 4, 'b': 3, 'c': 1, 'e': 1, 'd': 1})
>>> dict(Counter('aaaaabbbcdeffff'))
{'a': 5, 'c': 1, 'b': 3, 'e': 1, 'd': 1, 'f': 4}https://stackoverflow.com/questions/10390606
复制相似问题