Dict () vs {} in python, which is better?

I like to know what is the best way to declare a dictionary below the approaches and why?

>>>a=dict(one=2, two=3) # {"two":3, "one":2} >>>a={"two":3, "one":2} 
+8
python
source share
3 answers

You think that someone has already analyzed this (in terms of performance).

With CPython 2.7, using dict () to create dictionaries takes up to 6 several times longer and includes more memory allocation operations than literal syntax. Use {} to create dictionaries, especially if you are pre-populating them, unless the literal syntax works for your case.

+12
source share

Secondly, it is clearer, easier to read, and it’s good that there is a certain syntax for this, because this is a very common operation:

 a = {"two":3, "one":2} 

And this should be preferred in the general case. The performance argument is secondary, but even so, the {} syntax is faster.

+3
source share

In Python, you should always use literal syntax whenever possible. So, [] for lists, {} for dicts, etc. It’s easier to read by others, it looks better, and the interpreter converts it to bytecode, which is faster (special operation codes for containers instead of making function calls).

+1
source share

All Articles