cpython: 22e514e41fac (original) (raw)
Mercurial > cpython
changeset 87607:22e514e41fac 3.3
recommend OrderedDict for this FAQ (closes #19805) [#19805]
Benjamin Peterson benjamin@python.org | |
---|---|
date | Tue, 26 Nov 2013 23:05:25 -0600 |
parents | bab7dc2ffc16 |
children | ddbcb86afbdc dfadce7635ce |
files | Doc/faq/programming.rst |
diffstat | 1 files changed, 3 insertions(+), 27 deletions(-)[+] [-] Doc/faq/programming.rst 30 |
line wrap: on
line diff
--- a/Doc/faq/programming.rst
+++ b/Doc/faq/programming.rst
@@ -1193,34 +1193,10 @@ that final assignment still results in a
Dictionaries
============
-How can I get a dictionary to display its keys in a consistent order?
----------------------------------------------------------------------
-
-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.
+How can I get a dictionary to store and display its keys in a consistent order?
+-------------------------------------------------------------------------------
-A more complicated solution is to subclass dict
to create a
-SortedDict
class that prints itself in a predictable order. Here's one
-simpleminded implementation of such a class::
-
- class SortedDict(dict):
def __repr__(self):[](#l1.25)
keys = sorted(self.keys())[](#l1.26)
result = ("{!r}: {!r}".format(k, self[k]) for k in keys)[](#l1.27)
return "{{{}}}".format(", ".join(result))[](#l1.28)
__str__ = __repr__[](#l1.30)
-
-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.
-
+Use :class:collections.OrderedDict
.
I want to do a complicated sort: can you do a Schwartzian Transform in Python?
------------------------------------------------------------------------------