Skip to content

Commit

Permalink
Merge pull request #144 from amsehili/collections-OrderedDict
Browse files Browse the repository at this point in the history
Add `OrderedDict` to collections.rst
  • Loading branch information
yasoob committed Feb 7, 2017
2 parents 1777f63 + 3f86901 commit 0bf4816
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions collections.rst
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ their usefulness.
The ones which we will talk about are:

- ``defaultdict``
- ``OrderedDict``
- ``counter``
- ``deque``
- ``namedtuple``
Expand Down Expand Up @@ -82,6 +83,42 @@ sample code:
print(json.dumps(some_dict))
# Output: {"colours": {"favourite": "yellow"}}
``OrderedDict``
^^^^^^^^^^^^^^^^^^^

``OrderedDict`` keeps its entries sorted as they are initially inserted.
Overwriting a value of an existing key doesn't change the position of
that key. However, deleting and reinserting an entry moves the key to
the end of the dictionary.

**Problem:**

.. code:: python
colours = {"Red" : 198, "Green" : 170, "Blue" : 160}
for key, value in colours.items():
print(key, value)
# Output:
# Green 170
# Blue 160
# Red 198
# Entries are retrieved in an unpredictable order
**Solution:**

.. code:: python
from collections import OrderedDict
colours = OrderedDict([("Red", 198), ("Green", 170), ("Blue", 160)])
for key, value in colours.items():
print(key, value)
# Output:
# Red 198
# Green 170
# Blue 160
# Insertion order is preserved
``counter``
^^^^^^^^^^^^^^^

Expand Down

0 comments on commit 0bf4816

Please sign in to comment.