dict() vs { } in python which is better? [closed]
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}
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.
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.
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).