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

前端 未结 8 508
陌清茗
陌清茗 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:26

    Update: thanks for the responses. Removed speculation about copy-on-write.

    One other difference between {} and dict is that dict always allocates a new dictionary (even if the contents are static) whereas {} doesn't always do so (see mgood's answer for when and why):

    def dict1():
        return {'a':'b'}
    
    def dict2():
        return dict(a='b')
    
    print id(dict1()), id(dict1())
    print id(dict2()), id(dict2())
    

    produces:

    $ ./mumble.py
    11642752 11642752
    11867168 11867456
    

    I'm not suggesting you try to take advantage of this or not, it depends on the particular situation, just pointing it out. (It's also probably evident from the disassembly if you understand the opcodes).

提交回复
热议问题