Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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} 
like image 574
user1559873 Avatar asked Jun 13 '13 22:06

user1559873


People also ask

Which is faster dict or set in Python?

The fastest way to repeatedly lookup data with millions of entries in Python is using dictionaries. Because dictionaries are the built-in mapping type in Python thereby they are highly optimized.

When should you not use a dictionary Python?

Python dictionaries can be used when the data has a unique reference that can be associated with the value. As dictionaries are mutable, it is not a good idea to use dictionaries to store data that shouldn't be modified in the first place.

Why is dict faster than list?

The reason is because a dictionary is a lookup, while a list is an iteration. Dictionary uses a hash lookup, while your list requires walking through the list until it finds the result from beginning to the result each time.

Is Python dictionary slow?

Python is slow. I bet you might encounter this counterargument many times about using Python, especially from people who come from C or C++ or Java world. This is true in many cases, for instance, looping over or sorting Python arrays, lists, or dictionaries can be sometimes slow.


1 Answers

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.

like image 77
Brian Cain Avatar answered Sep 21 '22 15:09

Brian Cain