I find it annoying that Python dictionaries do not store keys in insertion order. Recently, I've started using OrderedDict, which is more convenient to use since it covers this drawback (for example, iterating over columns of a CSV file where the column order is supposed to match the key order of a dictionary).
That said, are there any distinct advantages that a dictionary has over an OrderedDict? If so, what are they?
The OrderedDict is a subclass of dict object in Python. The only difference between OrderedDict and dict is that, in OrderedDict, it maintains the orders of keys as inserted. In the dict, the ordering may or may not be happen. The OrderedDict is a standard library class, which is located in the collections module.
defaultdict is faster for larger data sets with more homogenous key sets (ie, how short the dict is after adding elements);
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 list is an ordered collection of data, whereas the dictionaries store the data in the form of key-value pairs using the hashtable structure. Due to this, fetching the elements from the list data structure is quite complex compared to dictionaries in Python. Therefore, the dictionary is faster than a list in Python.
A dictionary is a simpler data structure that takes up less space and is a bit faster. It only needs to maintain a hash table, while an OrderedDict
maintains both a hash table and a linked list.
If you don't care about the order of keys, go with the simpler option.
Also not to be overlooked, there's language level support for dicts. It's easy to type {k1: v1, k2: v2}
. That's another win for dicts. An unfair one, perhaps, but there you go.
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