正如其他答案所述,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标识符,并且 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 文字的 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}