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}
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With