Is there a difference between using a dict literal and a dict constructor?

前端 未结 10 2105
深忆病人
深忆病人 2020-11-28 02:26

Using PyCharm, I noticed it offers to convert a dict literal:

d = {
    \'one\': \'1\',
    \'two\': \'2\',
}

10条回答
  •  长情又很酷
    2020-11-28 02:46

    They look pretty much the same on Python 3.2.

    As gnibbler pointed out, the first doesn't need to lookup dict, which should make it a tiny bit faster.

    >>> def literal():
    ...   d = {'one': 1, 'two': 2}
    ...
    >>> def constructor():
    ...   d = dict(one='1', two='2')
    ...
    >>> import dis
    >>> dis.dis(literal)
      2           0 BUILD_MAP                2
                  3 LOAD_CONST               1 (1)
                  6 LOAD_CONST               2 ('one')
                  9 STORE_MAP
                 10 LOAD_CONST               3 (2)
                 13 LOAD_CONST               4 ('two')
                 16 STORE_MAP
                 17 STORE_FAST               0 (d)
                 20 LOAD_CONST               0 (None)
                 23 RETURN_VALUE
    >>> dis.dis(constructor)
      2           0 LOAD_GLOBAL              0 (dict)
                  3 LOAD_CONST               1 ('one')
                  6 LOAD_CONST               2 ('1')
                  9 LOAD_CONST               3 ('two')
                 12 LOAD_CONST               4 ('2')
                 15 CALL_FUNCTION          512
                 18 STORE_FAST               0 (d)
                 21 LOAD_CONST               0 (None)
                 24 RETURN_VALUE
    

提交回复
热议问题