Controlling the order of dict keys
In the Creating dictionaries – inserting and updating recipe we looked at the basics of creating a dictionary object. In many cases, we'll put items into a dictionary and fetch items from a dictionary individually. The idea of an order to the keys doesn't even enter into the problem.
There are some cases where we might want to display the contents of a dictionary. In this case, we often want to impose some order on the keys. For example, when we work with web services, the messages are often dictionaries encoded in JSON notation. In many cases we'd like to keep the keys in a particular order so that the message is easier to understand when it's displayed in a debugging log.
As another example, when we read data with the csv
module each row from a spreadsheet can be represented as a dictionary. In this case, we almost always want to keep the keys in a given order so that the dictionary follows the structure of the source file.
Getting ready
A dictionary is a...