liveBook · Manning

OrderedDict

As explained in Practices of the Python Pro

OrderedDict is a Python dictionary subclass that preserves insertion order and provides operations for explicitly rearranging entries.

OrderedDict is a Python dictionary class that preserves insertion order, making it useful when options must appear in a deliberate sequence. A menu can store keyboard shortcuts and option objects, then iterate over its items for consistent display. section 6.3.3

Ordered menu options

Use an ordered mapping for choices such as Add, List, Delete, and Quit. Iterating through options.items() prints each shortcut and its label in the specified order. section 6.3.3

Listing 6.12. Specifying and printing menu options
def print_options(options):
    for shortcut, option in options.items():
        print(f'({shortcut}) {option}')
    print()

...

if __name__ == '__main__':
    ...
    options = {
        'A': Option('Add a bookmark', commands.AddBookmarkCommand()),
        'B': Option('List bookmarks by date',
commands.ListBookmarksCommand()),
        'T': Option('List bookmarks by title',
commands.ListBookmarksCommand(order_by='title')),
        'D': Option('Delete a bookmark', commands.DeleteBookmarkCommand()),
        'Q': Option('Quit', commands.QuitCommand()),
    }
    print_options(options)

Shows how menu options map shortcuts to command objects and how iteration prints them. section 6.3.3

How Practices of the Python Pro covers it

How deep it goes
Explains the menu use case and iteration, but stops short of broader OrderedDict operations.
Examples
Uses a Bark command-line menu with shortcuts for adding, listing, deleting, and quitting bookmarks.
What it assumes
Assumes familiarity with dictionaries, key-value pairings, and iterating with items().
What you can do after
Apply it via Python's collections.OrderedDict to define and print menu choices in a chosen order.
How it connects
Connects dictionaries, iteration, menu options, presentation layers, and command objects.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Practices of the Python Pro. The section links point to the parts of the book it draws on.