dict() vs { } in python which is better?

PythonPython 2.7

Python Problem Overview


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}

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

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.

Solution 3 - Python

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).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1559873View Question on Stackoverflow
Solution 1 - PythonBrian CainView Answer on Stackoverflow
Solution 2 - PythonÓscar LópezView Answer on Stackoverflow
Solution 3 - PythonAnorovView Answer on Stackoverflow