You can't. Dictionaries store their keys in an unpredictable order, so the display order of a dictionary's elements will be similarly unpredictable.
This can be frustrating if you want to save a printable version to a file, make some changes and then compare it with some other printed dictionary. In this case, use the pprint module to pretty-print the dictionary; the items will be presented in order sorted by the key.
A more complicated solution is to subclass UserDict.UserDict to create a SortedDict class that prints itself in a predictable order. Here's one simpleminded implementation of such a class:
import UserDict, string
class SortedDict(UserDict.UserDict):
def \_\_repr\_\_(self):
result = []
append = result.append
keys = self.data.keys()
keys.sort()
for k in keys:
append("%s: %s" % (`k`, `self.data[k]`))
return "{%s}" % string.join(result, ", ")
\_\__str\_\_ = \_\_repr\_\_
This will work for many common situations you might encounter, though it's far from a perfect solution. The largest flaw is that if some values in the dictionary are also dictionaries, their values won't be presented in any particular order.
CATEGORY: programming