他の回答が述べているように、dictは関数呼び出しです。3 つの構文形式があります。
フォーム:
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
ただし、使用できる構文形式は他に 2 つあります。
がある:
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はマッピングであり、これがそれらの 1 つを 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}