python的dict(** kwarg)构造函数如何工作?

时间:2018-10-16 12:08:54

标签: python dictionary constructor

此dict构造函数如何将键-值对的键从标识符转换为字符串呢?

>>> a = dict(one=1, two=2, three=3)
>>> a
{'one': 1, 'two': 2, 'three': 3}
>>> dict[four] = 4
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    dict[four] = 4
NameError: name 'four' is not defined

我检查了帮助文档,但忽略了dict构造函数工作方式的签名。

    def __init__(self, seq=None, **kwargs): # known special case of dict.__init__
    """
    dict() -> new empty dictionary
    dict(mapping) -> new dictionary initialized from a mapping object's
        (key, value) pairs
    dict(iterable) -> new dictionary initialized as if via:
        d = {}
        for k, v in iterable:
            d[k] = v
    dict(**kwargs) -> new dictionary initialized with the name=value pairs
        in the keyword argument list.  For example:  dict(one=1, two=2)
    # (copied from class doc)
    """
    pass

0 个答案:

没有答案