43
votes

I like to know, which is the best practice to declare dictionary in below 2 approaches and why?

>>>a=dict(one=2, two=3)  # {"two":3, "one":2}
>>>a={"two":3, "one":2}
3
FWIW, there is one difference I have found. dict(zip(foo)) is possible. Not sure why {zip(foo)} is not possible in either python 2 or 3. I came here hoping to learn why. - netskink
Why is this question closed? People who voted to close it rather could have spent effort to improve it by adding criteria to define better instead of closing. - Mahori
"Which is better" without defining what "better" means is way to broad - Nico Haase

3 Answers

40
votes

Would you believe someone has already analyzed that (from a performance perspective).

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

16
votes

The second one is clearer, easier to read and it's a good thing that a specific syntax exists for this, because it's a very common operation:

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

And it should be preferred on the general case. The performance argument is a secondary concern, but even so, the {} syntax is faster.

11
votes

In Python you should always use literal syntax whenever possible. So [] for lists, {} for dicts, etc. It's easier for others to read, looks nicer, and the interpreter will convert it into bytecode that is executed faster (special opcodes for the containers, instead of performing function calls).