What's the difference between dict() and {}?

前端 未结 8 473
陌清茗
陌清茗 2020-12-12 13:53

So let\'s say I wanna make a dictionary. We\'ll call it d. But there are multiple ways to initialize a dictionary in Python! For example, I could do this:

相关标签:
8条回答
  • 2020-12-12 14:30

    Funny usage:

    def func(**kwargs):
          for e in kwargs:
            print(e)
        a = 'I want to be printed'
        kwargs={a:True}
        func(**kwargs)
        a = 'I dont want to be printed'
        kwargs=dict(a=True)
        func(**kwargs)
    

    output:

    I want to be printed
    a
    
    0 讨论(0)
  • 2020-12-12 14:31
    >>> def f():
    ...     return {'a' : 1, 'b' : 2}
    ... 
    >>> def g():
    ...     return dict(a=1, b=2)
    ... 
    >>> g()
    {'a': 1, 'b': 2}
    >>> f()
    {'a': 1, 'b': 2}
    >>> import dis
    >>> dis.dis(f)
      2           0 BUILD_MAP                0
                  3 DUP_TOP             
                  4 LOAD_CONST               1 ('a')
                  7 LOAD_CONST               2 (1)
                 10 ROT_THREE           
                 11 STORE_SUBSCR        
                 12 DUP_TOP             
                 13 LOAD_CONST               3 ('b')
                 16 LOAD_CONST               4 (2)
                 19 ROT_THREE           
                 20 STORE_SUBSCR        
                 21 RETURN_VALUE        
    >>> dis.dis(g)
      2           0 LOAD_GLOBAL              0 (dict)
                  3 LOAD_CONST               1 ('a')
                  6 LOAD_CONST               2 (1)
                  9 LOAD_CONST               3 ('b')
                 12 LOAD_CONST               4 (2)
                 15 CALL_FUNCTION          512
                 18 RETURN_VALUE        
    

    dict() is apparently some C built-in. A really smart or dedicated person (not me) could look at the interpreter source and tell you more. I just wanted to show off dis.dis. :)

    0 讨论(0)
提交回复
热议问题