How to do it...

  1. The following examples come from https://docs.python.org/3/library/collections.html#collections.OrderedDict. ordereddict_use.py, below, shows how to use OrderedDict to create a sorted dictionary:
      >>> from collections import OrderedDict      >>> d = {'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2}            # regular unsorted dictionary      >>> OrderedDict(sorted(d.items(), key=lambda t: t[0]))            # dictionary sorted by key      OrderedDict([('apple', 4), ('banana', 3), ('orange', 2),                    ('pear', 1)])      >>> OrderedDict(sorted(d.items(), key=lambda t: t[1]))            # dictionary sorted by value      OrderedDict([('pear', 1), ('orange', 2), ('banana', 3),                    ('apple', 4)])      >>> OrderedDict(sorted(d.items(), key=lambda t: len(t[0])))   # dictionary sorted by length of ...

Get Secret Recipes of the Python Ninja now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.