Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advantages of Dict over OrderedDict [duplicate]

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?

like image 386
Sean Saito Avatar asked Jul 03 '15 01:07

Sean Saito


People also ask

What is the difference between dict and OrderedDict?

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.

What are the advantages of using Defaultdict over dict?

defaultdict is faster for larger data sets with more homogenous key sets (ie, how short the dict is after adding elements);

Should I use dict () or {}?

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.

Why dict is faster than list?

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.


1 Answers

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.

like image 171
John Kugelman Avatar answered Sep 26 '22 02:09

John Kugelman