What is the difference between dict () and {}?

So let's say I want to make a dictionary. We will call him d . But there are several ways to initialize a dictionary in Python! For example, I could do this:

 d = {'hash': 'bang', 'slash': 'dot'} 

Or I could do this:

 d = dict(hash='bang', slash='dot') 

Or this, with curiosity:

 d = dict({'hash': 'bang', 'slash': 'dot'}) 

Or that:

 d = dict([['hash', 'bang'], ['slash', 'dot']]) 

And a number of ways using the dict() function. Thus, it is obvious that one of the things dict() provides is flexibility in syntax and initialization. But that is not what I am asking.

Say I had to make d just an empty dictionary. What happens behind the scenes of the Python interpreter when I do d = {} versus d = dict() ? Are these just two ways to do the same? Does {} an extra dict() call? Does (even a minor) have more overhead than others? Although the question is really completely unimportant, it is a curiosity that I would like to answer.

+48
python instantiation initialization
Mar 19 '09 at 21:19
source share
7 answers
 >>> 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 () seems to be embedded in C. A really smart or dedicated person (not me) could look at the source of the translator and tell you more. I just wanted to show dis.dis. :)

+60
Mar 19 '09 at 21:25
source share

Regarding performance:

 >>> from timeit import timeit >>> timeit("a = {'a': 1, 'b': 2}") 0.424... >>> timeit("a = dict(a = 1, b = 2)") 0.889... 
+29
Mar 19 '09 at 21:41
source share

@Jacob: there is a difference in the distribution of objects, but they are not copied to the record. Python allocates a โ€œfree listโ€ of a fixed size, where it can quickly highlight dictionary objects (until it fills up). Layers highlighted using the {} syntax (or calling C on PyDict_New ) can come from this free list. When the dictionary is no longer referenced, it is returned to the free list and this memory block can be reused (although the fields are reset first).

This first dictionary immediately returns to the free list, and the next will reuse its memory space:

 >>> id({}) 340160 >>> id({1: 2}) 340160 

If you save the link, the following dictionary will appear from the following free slot:

 >>> x = {} >>> id(x) 340160 >>> id({}) 340016 

But we can remove the link to this dictionary and release its slot again:

 >>> del x >>> id({}) 340160 

Since the syntax {} processed in byte code, it can use the optimization mentioned above. On the other hand, dict() treated like a regular class constructor, and Python uses a shared memory allocator that does not follow an easily predictable pattern, such as a free list.

Also, looking at compile.c from Python 2.6, with the syntax {} , the hash table seems to be pre-sized based on the number of elements it stores, which is known during parsing.

+22
Mar 25 '09 at 12:28
source share

Basically, {} is syntax and is processed at the language and bytecode level. dict () is another option with a more flexible initialization syntax. Note that dict () was only added in the middle of the 2.x series.

+6
Mar 19 '09 at 23:15
source share

Update: thanks for the answers. Assumptions about copying to record are eliminated.

Another difference between {} and dict is that dict always highlights a new dictionary (even if the content is static), while {} does not always do this (see mgood answer , when and why):

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

gives:

 $ ./mumble.py
 11642752 11642752
 11867168 11867456

I do not suggest that you try to take advantage of it or not, it depends on the specific situation, just pointing to it. (This is also obvious from a disassembly if you understand the operation codes).

+4
Mar 20 '09 at 18:44
source share

dict () is used when you want to create a dictionary from an iteration, for example:

 dict( generator which yields (key,value) pairs ) dict( list of (key,value) pairs ) 
+2
Apr 29 '11 at 21:50
source share

To create an empty set, we must use a set of keywords in front of it ie set() creates an empty set, where, as in the dict, only flower brackets can create an empty dict

Let's look at an example

 print isinstance({},dict) True print isinstance({},set) False print isinstance(set(),set) True 
-one
May 31 '16 at 14:30
source share



All Articles