The OrderedDict collection

The OrderedDict collection is a Python dictionary with an added feature. The order in which keys were inserted is retained.

One common use for OrderedDict is when processing HTML or XML files, where the order of objects must be retained, but objects might have cross-references via the ID and IDREF attributes. We can optimize the connections among objects by using the ID as a dictionary key. We can retain the source document's ordering with the OrderedDict structure.

With release 3.7, the built-in dict class makes the same guarantee of preserving the order in which dictionary keys were inserted. Here's an example:

>>> some_dict = {'zzz': 1, 'aaa': 2}
>>> some_dict['mmm'] = 3
>>> some_dict
{'zzz': 1, 'aaa': 2, 'mmm': 3}

In earlier releases of Python, the order of keys in a dictionary were not guaranteed to match the order in which they were inserted. The ordering of keys used to be arbitrary and difficult to predict. The OrderedDict class added the insertion order guarantee in these older releases of Python. Since the order of the keys is now guaranteed to be the order in which keys were inserted, the OrderedDict class is redundant. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset